Double char pointer Operations
Suppose I have char **argv
.
First, how can I print all lines in argv
? I tried the following:
char *temp;
temp = *argv; // Now points to the first string?
while (temp != NULL) {
printf("%s ", temp);
temp++;
}
Here, when temp
incremented, it only skips one character. Why is this happening? I know it argv
is an array that contains points. Each pointer points to an array char*
. If so, why doesn't it work? I know that since it temp
has a type char
, incrementing that pointer will increment it by 1
char (or byte). If so, how can I increment the pointer to the next array and print that string?
source to share
It only skips one character because it temp
is a pointer to char
. By adding one of these, you are telling the compiler to move the pointer to point to the next one char
in memory.
argv
- an array of pointers. What you need to do is go to the next pointer at each iteration. Something like:
char **temp = argv; // temp is a pointer to a *pointer*, not a pointer to a *char*
while (*temp != NULL) {
printf("%s ", *temp);
temp++;
}
source to share
First, you need to understand what it is char** argv
. It is an array of pointers to char. The pointers in this array do not have to be somewhere near each other in the address space. What you want is this:
char** temp;
temp = argv;
while(temp != argv + argc) {
printf("%s ", temp);
temp++;
}
You must have a pointer to the first element of the array to pointers to char. Add instead.
source to share