0

I have defined a constant array of strings as

static const char *Props[] = {"Cp", "Cv", "Mu", "H"};

I get error while executing the following:

while(*Props) printf("%s\n", *Props++);

Error message is:

C/test.c:38:45: error: lvalue required as increment operand

Can anybody please explain why I get this error?

3
  • 1
    The array itself is a constant. It can not be changed. static const char *Props[] = {"Cp", "Cv", "Mu", "H", NULL}; const char **p = Props; while(*p) printf("%s\n", *p++); Commented Dec 1, 2016 at 15:15
  • But the program executes when I write while(*Props) printf("%s\n", *(Props+1)); Why? Commented Dec 3, 2016 at 13:09
  • Props+1 does not change Props. Props+1 does not mean Props = Props+1 Commented Dec 3, 2016 at 13:18

3 Answers 3

2

Array designators are non-modifiable lvalues. You may not change them. What you need is the following

static const char *Props[] = {"Cp", "Cv", "Mu", "H"};

for ( size_t i = 0; i < sizeof( Props ) / sizeof( *Props ); i++ )
{
    puts( Props[i] );
}

Another approach is to add a sentinel value to the array. For example

static const char *Props[] = {"Cp", "Cv", "Mu", "H", NULL };

for ( const char **s = Props; *s; s++ )
{
    puts( *s );
}
Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't work work the same reason as int array [] = {1,2}; array++; doesn't work.

You can't apply ++ on an array type. You would need a pointer to the first item of the array instead. Thus one solution would have been to do this:

const char** ptr = &Props[0]; 
while(*ptr) printf("%s\n", *ptr++);

But that's pretty horrible code and also contains another bug, namely the lack of an end condition in the array. For this solution to work, the array should have been declared as {"Cp", "Cv", "Mu", "H", NULL};.

Don't do weird things like this just because you can though. Just use a for loop with an integer iterator, as demonstrated in another answer.

Comments

1

Only for the purposes of satisfying the requirements of this odd question:

#include <stdio.h>

static void
print_props(void)
{
    static const char *Props[] = {"Cp", "Cv", "Mu", "H"};
    const char **b = Props;
    const char **e = Props + sizeof(Props)/sizeof(Props[0]);

    do {
        puts(*(b++));
    } while (b != e);
    return;
}

int
main(void)
{
    print_props();
    return 0;
}

However, just use a for loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.