I have a simple doubt in char arrays. I have a structure:
struct abc {
char *charptr;
int a;
}
void func1()
{
func2("hello");
}
void func (char *name)
{
strcpy(abc.charptr, name); // This is wrong.
}
This strcpy will result in a crash since I do not have any memory allocated to the charptr.
The question is : For mallocing this memory, can we do
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?
Is this right ?
If you were to use malloc() you need to remember to make room for the null-terminator. So use malloc(strlen(name)+1) before calling strcpy().
But in this case you should just use strdup() which does the allocation and copying in one go:
abc.charptr = strdup(name);
The memory returned by strdup() has been allocated with malloc() and hence must be disposed of with a call to free().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With