fizzy drink fizzy drink - 26 days ago 9
C Question

printing values in array pointer in C

I can't seem to wrap my head around a problem. What am I missing?

Consider the following

int main(int argc, char *argv[]) {
while ( *argv ) {
printf("argv[] is: %s\n", *argv);
++argv;
}

return 0;
}


This prints out every value of argv. So a command line such as
./example arg1 arg2
would output the following:

`argv[] is: ./example`
`argv[] is: arg1`
`argv[] is: arg2`


Now consider the following (which I am having trouble with):

int main(void) {
char *days[] = {
"Sunday",
"Monday",
"Tuesday"
};
while ( *days ) {
printf("day is %s\n", *days);
*days++;
}

return 0;
}


If I try to compile, I get error
cannot increment value of type 'char *[3]'


If I change
*days++
to
(*days)++
it compiles. If I run it, it runs forever and eventually fails with
bus error
.

However, it does not iterate through every value of
days[]
. I even tried putting in a Null pointer in the form of
'\0'
and
"\0"
in the days array to no effect.

What am I missing?

Answer

You have several error in the your code:

  1. There is difference between variable "argv" and constant "days". Variable can be changed, constant array label - cannot.

  2. In your array, is missing terminator NULL at end of the array.

  3. *days++; is senseless in this case. This is dummy return values of days, and increment "days" thereafter. Enough just "days++".

Thus, your code must be like:

include

int main(void) {
    char *days[] = {
        "Sunday",
        "Monday",
        "Tuesday",
        NULL
    };
    char **d = days;
    while ( *d ) {
        printf("day is %s\n", *d);
        d++;
    }

    return 0;
}