As mentioned in the comments, the problem with your attempted strcpy
call is that your destination (the string
member of your data
) isn't a pointer to valid memory. (I am assuming that your invalid syntax, strcpy((*data).string = "Hello!")
is a typo, and that your real code has something like strcpy((*data).string, "Hello!")
– otherwise, it won't even compile, so you won't get a segmentation fault.)
There are several approaches to fix this, depending on what you actually want to happen. First, as also mentioned in the comments, you can just copy the pointer to the destination, like this1:
data->string = "Hello!";
However, this may not be what you want, because, if the source is not actually a literal, but a modifiable string, then, after that assignment, any changes to the source will also apply to your copy.
If you want a copy of the source data, you will need to allocate sufficient space for it, then call strcpy
; like this:
#include <stdlib.h> // For malloc
const char* src = "Hello!";
data->string = malloc(strlen(src) + 1); // Add 1 for the required nul-terminator
strcpy(data->string, src);
However, the strdup
function2 does the job of the above malloc
and strcpy
calls in one fell swoop:
data->string = strdup("Hello!");
In each of the above two cases, be sure to call free(data->string)
when you're finished.
1 Note that you can use the "member access through pointer" (->
) operator, rather than dereferencing and then using the .
operator: data->number = 5
is equivalent to your (*data).number = 5
.
2 Some compilers/platforms may not support the strdup
function, but it is part of the ISO C Standard from C23