This is likely a very beginner question so please go easy on me…
I have a struct array as follows
struct Data {
int lineno;
char* line[10];
}
struct Data datas[20] = {{ 0, NULL }};
I’m trying to deep copy a char * [] into an array element yet I keep getting seg faults.
I’ve attempted the following
for (int i = 0; i < 20; i++) {
strcpy(datas[slot].line[i], line[i]);
}
but this doesn’t work.
I thought that my problem was attempting to copy null values in line so I tried the following
for (int i = 0; i < 20; i++) {
if (line[i])
strcpy(datas[slot].line[i], line[i]);
}
but this doesn’t work either.
>Solution :
You need to allocate memory before copying the string. Most implementations support strdup
to both allocate memory and copy the string:
for (int i = 0; i < 20; i++) {
datas[slot].line[i] = strdup(line[i]);
}
If your implementation doesn’t support strdup
, you could create your own:
#include <stdlib.h>
char *StrDup(const char* str) {
size_t len = strlen(str) + 1;
char *res = malloc(len);
if (res) memcpy(res, str, len);
return res;
}