Possible Duplicate:
What is the difference between char s[] and char *s in C?
Difference between char *str = “…” and char str[N] = “…”?
I have a structure defined as:
typedef struct
{
bool configured;
bool active;
uint32 lastComms;
uint32 rxChRvdTime;
char *name;
}vehicle;
and I initialize it as follows:
static vehicle *myVehicle;
When I want to initialize the name, I use:
myVehicle->name = "helloworld";
And this works fine. But when I wan’t to set it to something other than a string literal, I seem to run into problems.
char *tmpName = "foobar";
strcpy(myVehicle->name, tmpName);
So why doesn’t strcpy work? Do I somehow need to preallocate the string size in the structure before hand? Should I not be using a pointer for the ‘name’ field, since there can only be one vehicle?
You need to allocate memory to copy into:
as
myVehicle->nameis an uninitialisedchar*. If youmalloc()you need tofree(). The assignment to the string literal works because you makingnamepoint to the address of the string literal, which exists for the lifetime of the program.But before this, you need to allocate memory for
myVehicleitself:or just make
myVehiclean object rather than a pointer: