Reputation: 33
I am trying to understand the concept of array of char pointers in C. In this basic example I try to get the number of strings using the x++ operator but, unfortunately I get a compiler error because maybe I try to access an extra region of memory but I shoudn't? Thanks for any help.
#include <stdio.h>
int main()
{
char *argv[]= {"hello","world"};
int num = 0;
while (argv[num++] != NULL){
printf("num value: %i\t %c\n",num,*argv[num-1]);
}
printf("Final num value: %i\n",num);
return 0;
}
Upvotes: 1
Views: 65
Reputation: 35154
You are exceeding array bounds since
while (argv[num++] != NULL)
will stop when argv[num]
is NULL
, yet argv[]
's dimension is 2
, and both entries are != NULL
.
You could write...
char *argv[]= {"hello","world",NULL};
and it should work with your end condition as is.
BTW: you are aware that argv[]
is often used as name for the parameters to function main
, i.e. int main(int argc, char* argv[])
, which represent the command line arguments when your program gets called, are you? When you use the function main
-parameter, I think that the last valid element of it will by NULL
by definition (cf., for example, this online C11 standard draft):
5.1.2.2.1 Program startup
....
(2) If they are declared, the parameters to the main function shall obey the following constraints:
argv[argc] shall be a null pointer.
If you create your "own" local argv[]
-thing, however, you have to do this explicitly on your own.
Upvotes: 6