Reputation: 116263
This is my code:
typedef struct{
char name[64];
} Cat;
Cat createCat(char name[64]) {
Cat newCat;
newCat.name = name;
return newCat;
}
It compiles with the following error message:
incompatible types when assigning to type 'char[64]' from type 'char *'
What am I doing wrong here?
Upvotes: 0
Views: 504
Reputation: 1990
Your code has two bugs. The first is that you are allocating memory on the stack. Whenever you declare a variable like this:
int hello = 5;
char test;
Cat newCat;
You are allocating memory on the stack. This memory is freed as soon as the function returns. To make something more permanent, you need to manually allocate memory in the heap with the malloc function. This memory will remain valid until you release it at a later date by calling free()
. Additionally, you need to use strncpy()
to copy strings, you can not simply copy the pointer.
Cat* createCat(char* name)
{
Cat* newCat = malloc(sizeof(Cat));
if(!newCat)
{
printf("Error allocating memory for cat\n");
exit(-1);
}
//copy in the string, leave a null terminator on the string
strncpy(newCat.name, name, 63);
newCat.name[63] = '\0';
return newCat;
}
Upvotes: 0
Reputation: 5784
Yikes. You're returning an automatic (stack-based) variable from a function. That will die horribly when the stack frame is popped and the memory goes away. You need to dynamically allocate a Cat
structure and copy the name
data into it. Don't forget to call free()
when you're done with the memory.
Cat *createCat(char name[64])
{
Cat *tmpCat;
tmpCat=malloc(sizeof(Cat));
strncpy(Cat.name,name,64); // <- or 63 to make sure name is NULL-terminated
return tmpCat;
}
Upvotes: 0
Reputation: 121961
Array decay to pointers when passed to functions. So:
Cat createCat(char name[64]) {
is the same as:
Cat createCat(char* name) {
and the line:
newCat.name = name;
is attempting to assign a char*
to a char[]
, as the error states. As Mystical has already commented, you need to use memcpy()
or strcpy()
(or strncpy()
) to copy name
to newCat.name
. If you use memcpy()
you must remember to null terminate newCat.name
.
Upvotes: 7