Reputation: 11
typedef struct Symbol{
char varName[16];
} Symbol;
...............
Symbol *newSymbol = malloc(sizeof(Symbol));
const char space[2] = " ";
char *String = "Name Test";
//break off the first word from String and put it into name
char *name;
name = strtok(String,space);
//convert the char * to char[16]
char nameArray[16];
strcpy(nameArray,name);
//set newSymbol->varName to the newly created char[16]
newSymbol->varName = nameArray
I have a char *
called String
. In my actual program, it is read from a file using fgets
, I am just calling it "Name Test" for the purposes of this example. I want to take the first word of the string and assign it as the varName
in a Symbol
. So what should happen is newSymbol->varName
is set to "Name". Because strtok
returns a char *
but I need a char[16]
for the struct, I must convert the char *
to a char[16]
.
However, I get this error:
"Error: incompatible types when assigning to type 'char[16]' from type 'char*'
newSymbol -> varName = nameArray;
So, it seems like strcpy it not actually converting the char *
to a char[16]
. Even after declaring a char[16]
and telling strcpy
to put the contents of the char *
into it, I still have a char *
instead of a char[16]
. I need to make it work without changing the struct, so that is not an option here.
How can I convert a char *
into a char[16]
?
Upvotes: 1
Views: 386
Reputation: 180286
So, it seems like strcpy it not actually converting the char* to a char[16].
No, the problem is that C does not provide for assigning to (whole) arrays. newSymbol->varName
is an array of 16 char
. You can assign to elements of that array, and you can copy into it with strcpy()
or a similar function, but you cannot assign to the whole array.
In your particular code, I'd dispense with variable nameArray
, changing this ...
strcpy(nameArray,name);
... to this:
strcpy(newSymbol->varName, name);
(Or perhaps to a similar usage of strncpy()
, to protect from overrunning the array bounds.)
Upvotes: 2
Reputation: 206607
You cannot assign the contents of an array using the regular assignment operator in C.
You can use strcpy
for strings and memcpy/memset
for other data types. (You could use memcpy/memset
for strings too but strcpy
is simpler)
Instead of
newSymbol -> varName = nameArray;
use
strcpy(newSymbol -> varName, nameArray);
Upvotes: 2