Peterdk
Peterdk

Reputation: 16005

How to properly copy char array to char array?

I am quite a newbie on C and am trying to get a C routine working.

const char *filenames[entry_count];
for (i = 0; i < entry_count; i++) {
    char filename_inzip[256];
    unz_file_info file_info;
    err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip,
            sizeof(filename_inzip), NULL, 0, NULL, 0); 

    //This doesn't work. My array gets filled with the last entry over and over.
    filenames[i] = filename_inzip; //Option 1

    //Here I get SIGSEV errors, or gibberish in output when debugging values
    strcpy(filenames[i], filename_inzip); //Option 2
}

I guess the first assignment doesn't work because it just points to the same temporary memory address of the char[256] in the loop.

The second option doesn't work I think because I haven't use malloc or similar.

How would I get a properly filled array?

Upvotes: 0

Views: 557

Answers (1)

simonc
simonc

Reputation: 42165

You're correct that you need to allocate memory in the second option.

filenames[i] = strdup(filename_inzip);

is the easiest way of doing this.

strdup is a Posix function rather than standard C. If it isn't available for you

filenames[i] = malloc(strlen(filename_inzip)+1);
if (filenames[i] != NULL) {
    strcpy(filenames[i], filename_inzip);
}

does an equivalent job

Note that you'll also have to call free for each array element you allocate later in your program.

Upvotes: 2

Related Questions