ambuli
asked on
C pointer question
Hi there,
The following small code crashes when executing. What is
The following small code crashes when executing. What is
typedef struct{
char *name;
}my_struct;
void copy_from(char *value)
{
//value = "somevalue"; I tried this one with the same problem
strcpy(value, "somevalue");
}
void copy_another(my_struct *table)
{
copy_from(table->name);
}
int main()
{
my_struct my;
copy_another(&my);
printf("%s", my.name );
return 0;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Alternatives are :
1) use an array instead of a pointer :
typedef struct{
char name[16];
} my_struct;
The disadvantage is that there is a maximum size for the name field (and you have to always keep that in mind so you never write past the end of the buffer).
2) allocate some memory for the pointer :
my_struct my;
my.name = (char*) calloc(16, sizeof(char));
copy_another(&my);
printf("%s", my.name );
The advantage here is that you can dynamically size the name field.
3) duplicate the string (assuming that strdup is available on your system - otherwise you'll have to implement it) :
1) use an array instead of a pointer :
typedef struct{
char name[16];
} my_struct;
The disadvantage is that there is a maximum size for the name field (and you have to always keep that in mind so you never write past the end of the buffer).
2) allocate some memory for the pointer :
my_struct my;
my.name = (char*) calloc(16, sizeof(char));
copy_another(&my);
printf("%s", my.name );
The advantage here is that you can dynamically size the name field.
3) duplicate the string (assuming that strdup is available on your system - otherwise you'll have to implement it) :
typedef struct{
char *name;
}my_struct;
void copy_another(my_struct *table)
{
table->name = strdup("somevalue");
}
int main()
{
my_struct my;
copy_another(&my);
printf("%s", my.name );
return 0;
}
>> value = "somevalue" and it crashed as well.
Yes, you can't put it in the copy_from method, since it works on a local copy of the pointer. I should have said that explicitly.
Yes, you can't put it in the copy_from method, since it works on a local copy of the pointer. I should have said that explicitly.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks a lot. I learnt something today :-)
ASKER
Yes, I tried
value = "somevalue" and it crashed as well. How can I correct it.