0

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?

1
  • filenames[i] is not a char array. It's a pointer. Commented Sep 5, 2013 at 16:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, will I need to use a loop and then call free on each?
Yes. Take care not to call free on any element whose value is unassigned however. Behaviour of free(NULL) is well defined so setting all elements to NULL at the start of your code would allow you to just loop through indexes [0..entry_count] later on without worrying about how many elements were actually allocated.
I guess there's not a way to free the complete array with a single call and not in a loop?
No. As a general rule, every call to malloc must have exactly one later matching call to free. If you call malloc in a loop you should therefore expect to later call free in a loop also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.