Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deep copy char * array into struct?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading