0

Working in C, I'm filling an array with char* return values from a function

 char* files[4][12];
 int i = 0;
 for (;;)
    {
      char* file = get_value();
      strcpy(files[i],file);
      i++;
      if (i > 4 || external_condition)
      break;

     }

      // When I break out of
      // my for loop the following
      // code executes

      for (i = 0; i < 5; i++)
       {
        if (files[i] != NULL)
        manipulate(files[i]);
       }

My problem is that if I break out of the first for loop without assigning values to all elements of files, my comparison in the second for loop fails. If only files[0] and files[1] have content, the loop processes files[2],file[3] and files[4] anyway.

1
  • 2
    One problem is that you are doing strcpy(files[i],file); without allocating any memory for the pointer files[i]. This will result in undefined behavior. Commented Sep 1, 2012 at 19:45

2 Answers 2

3

files is declared as an "array of arrays of pointers to char". Or if you prefer, as a two-dimensional array of pointers to char.

So files[i] is of type "array of pointers to char" but you use it as just a "pointer to char". That is wrong.

That said, it is not clear what you want to do... maybe just:

char files[5][13];

will make more sense. 13 because you likely need 13 char strings (8.3 are 8+3+1=12 plus 1 for the ending NUL), and you seem to use 5 of them. Then initialize them to zero:

memset(files, 0, sizeof(files));

And use the check:

if (files[i][0])

to check if a text is initialized.

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

4 Comments

Or maybe char files[4][13], considering that an 8.3 filename plus a nul terminator occupies 13 bytes.
@SteveJessop: Good thought. Updated.
No need for the parentheses for sizeof files.
@veer: I know... sizeof is an operator, but I like it this way, as if it were a function, I find it more readable. You don't need most whitespaces or line feeds, either, but you wouldn't remove them, will you?
0

char* files[4][12] is a 2D array of char *, not char. Perhaps you meant your code to be as follows... I suggest you listen to what others have said. I'm merely posting a shortened version that still works.

char files[5][12] = { { 0 } };
int i = 0;

do {
  strcpy(files[i], get_value());
} while (++i <= 4 && !external_condition);

while (i) {
  manipulate(files[--i]);
}

1 Comment

You have the strcpy() arguments swapped.

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.