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?
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
Access Array Elements Using Pointers data[0] is equivalent to *data and &data[0] is equivalent to data. data[1] is equivalent to *(data + 1) and &data[1] is equivalent to data + 1. data[2] is equivalent to *(data + 2) and &data[2] is equivalent to data + 2.
16) What is the output of C program with array of pointers to strings.? Explanation: It is an array of arrays. Using an array of pointers to strings, we can save memory.
You have several errors in your code:
There is difference between variable argv
and constant days
. Variable can be changed, constant array label - cannot.
In your array, terminator NULL is missing at the end of the array.
*days++;
is senseless in this case. This is a dummy and returns value of days
, and increment days
thereafter. It is enough to just use days++
.
Thus, your code must be like:
#include <stdio.h>
int main(void) {
char *days[] = {
"Sunday",
"Monday",
"Tuesday",
NULL
};
// Your style
char **d = days;
while ( *d ) {
printf("day is %s\n", *d);
d++;
}
// Or, more "scholastic" code
for(const char **d = days; *d; d++)
printf("day is %s\n", *d);
return 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With