Search code examples
carrayslvalue

Stepping through an array of pointers to strings - "lvalue required as increment operand"


I'm confused about this program which I'm going to state here. I wrote two simple programs to print a list of strings. First I made an array of pointers to the strings. And this is how I tried to do it

#include <stdio.h>

int main()
{
    int i = 2;
    char *a[] = {"Hello", "World"};

    while (--i >= 0) {
        printf("%s\n", *a++); // error is here.
    }

    return 0;

}

I need it to print

Hello
World

but there is compilation error and it says,

lvalue required as increment operand.

Then I changed the program to the following

#include <stdio.h>

void printout(char *a[], int n)
{
    while (n-- > 0)
        printf("%s\n", *a++);
}

int main()
{
    int i = 2;
    char *a[] = {"Hello", "World"};

    printout(a,i);
    return 0;

}

Then it worked as expected.

My question is, What's the difference happen when I pass the array name to a function? Why didn't it work the first time (I suspect that "array names cannot be modified" is the reason But WHY in the second program, it allowed me to increment)?


Solution

  • *a++
    

    ++ requires its operand to be a modifiable lvalue.

    In the first example, a is an array. In the second example, when passed to a function as argument, the array decays to a pointer (to its first element), so the code compiles.