Alan
Alan

Reputation: 1265

c string array comparison

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.

Upvotes: 0

Views: 496

Answers (2)

obataku
obataku

Reputation: 29636

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]);
}

Upvotes: 0

rodrigo
rodrigo

Reputation: 98338

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.

Upvotes: 3

Related Questions