VasandGVD said:
hi! I have the following code...
struct my_struct {
char str[256];
};
int main(int argc, char *argv[]) {
struct my_struct *ms;
char *str_ptr;
return 0;
}
the my_struct pointer *ms points to a filled struct.
(Really? Not in the code above, it doesn't.)
how can i copy the contents of the char str[256] array to the char
*str_ptr pointer?
You can't. The contents of `str` are a bunch of characters, but
a `char*` variable needs a pointer value (or null).
You have two choices.
(a) `char *str_ptr = ms->str;`
This doesn't copy any characters; it makes `str_ptr` (horrible name,
by the way) point to the first character of `str`. However, if
`*ms` every goes away (it was mallocated, and gets freed; or it
is an automatic variable, and we leave the function it was declared
in), `str_ptr` becomes invalid.
(b) Make `str_ptr` point to some other big-enough store and copy
the characters there. (I see Nick has already mentioned this.)
char *str_ptr = SOME_BIG_ENOUGH_STORE;
memcpy( str_ptr, ms->str, 256 );
(Don't be tempted to use `strcpy` in place of `memcpy` unless you
/know/ that `ms->str` refers to a string.)
`SOME_BIG_ENOUGH_STORE` might be an array of >= 256 characters,
or the result of a successful `malloc(N)`, N >= 256 characters.