My structure looks as follows:
typedef struct {
unsigned long attr;
char fileName[128];
} entity;
Then I try to assign some values but get an error message...
int attribute = 100;
char* fileNameDir = "blabla....etc";
entity* aEntity;
aEntity->attr = attributes;
aEntity->fileName = fileNameDir;
Compiler tells me:
Error: #137: expression must be a modifiable lvalue aEntity->fileName = fileNameDir;
Why cant I assign here this character to the one in the structure?
Thanks
The problem lies in the fact that you cannot just use a pointer without initialising it to a variable of that same datatype, which in this is a entity variable. Without this, the pointer will point to some random memory location containing some garbage values. You will get segmentation faults when trying to play with such pointers.
The second thing to be noted is that you can't directly assign strings to variables with the assignment operator(=). You have to use the strcpy() function which is in the string.h header file.
The output of the code is: 100 blabla......etc
You should be copying the filename string, not changing where it points to.
Use strncpy():
The major problem is that you declared a pointer to a struct, but allocated no space to it (unless you left some critical code out). And the other problems which others have noted.
Are you writing C or C++? There is no language called C/C++ and the answer to your question differs depending on the language you are using. If you are using C++, you should use
std::string
rather than plain old C strings.There is a major problem in your code which I did not see other posters address:
declares
aEntity
(should beanEntity
) as a pointer to anentity
but it is not initialized. Therefore, like all uninitialized pointers, it points to garbage. Hence:invokes undefined behavior.
Now, given a properly initialized
anEntity
,anEntity->fileName
is an array, not a pointer to a character array (see question 6.2 in the C FAQ list). As such, you need to copy over the character string pointed to byfileNameDir
to the memory block reserved foranEntity->fileName
.I see a lot of recommendations to use
strncpy
. I am not a proponent of thinking ofstrncpy
as a safer replacement forstrcpy
because it really isn't. See also Why isstrncpy
insecure?See
strncat
.For char fileName[128], fileName is the array which is 128 char long. you canot change the fileName. You can change the content of the memory that filename is pointing by using strncpy( aEntity->fileName, fileNameDir, 128 );