1

This is in reference to a solution posted on: Looping a fixed size array without defining its size in C

Here's my sample code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    static const char *foo[] = {
           "this is a test",
           "hello world",
           "goodbye world",
           "123", 
           NULL
    };

    for (char *it = foo[0]; it != NULL; it++) {
        printf ("str %s\n", it);
    }

    return 0;

}

Trying to compile this gives:

gcc -o vararray vararray.c
vararray.c: In function ‘main’:
vararray.c:14: warning: initialization discards qualifiers from pointer target type
vararray.c:14: error: ‘for’ loop initial declaration used outside C99 mode
Community
  • 1
  • 1
randombits
  • 47,058
  • 76
  • 251
  • 433
  • Clarify: C99 mode "forbidden", and you need the work-around -- OR -- you are open to using C99 mode? – Roboprog Dec 28 '09 at 16:16

5 Answers5

7

Besides the initialization in the for loop, you're incrementing in the wrong place. I think this is what you mean (note that I'm not exactly a C guru):

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    static const char *foo[] = {
           "this is a test",
           "hello world",
           "goodbye world",
           "123", 
           NULL
    };
    const char **it;
    for (it=foo; *it != NULL; it++) {
        printf ("str %s\n", *it);
    }

    return 0;

}
balpha
  • 50,022
  • 18
  • 110
  • 131
6
  1. Your loop variable it is of type char*, the contents of the array are of type const char*. If you change it to be also a const char* the warning should go away.

  2. You declare it inside the for statement, this is not allowed in C before C99. Declare it at the beginning of main() instead.
    Alternatively you can add -std=c99 or -std=gnu99 to your gcc flags to enable the C99 language features.

sth
  • 222,467
  • 53
  • 283
  • 367
1

Use -std=c99 option when compiling your code in order to use the C99 features.

Change it to const char* type ( to remove the warnings)

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
0

Before C99, declaring that character pointer in the for loop is non-standard.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
0

You need two things to have this compile without warnings: declare the iterator const char* it, and do it at the beginning of the function and not in the loop statement.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171