Lets say I have the following variables:
char c[] = "ABC";
char *ptr = &c;
char **ptr2 = &ptr;
I know I can iterate over a pointer to an array of char, this way:
int i;
for(i=0; i<3; i++){
printf("TEST******************, %c\n", ptr[i]);
}
How do I iterate over a pointer to a pointer?
For your example:
int i;
for(i=0; i<3; i++){
printf("TEST******************, %c\n", (*ptr2)[i]);
}
Suppose:
6 char c[] = "ABC";
7
8 char *ptr = &c;
9 char *ptr2 = ptr;
10 char **ptr3 = &ptr;
In this scenario:
ptr
represents an address of c
ptr2
represents an address of ptr
. A pointer to a pointer
ptr3
is a value stored in ptr
, which is an address of c
.
**ptr3=&ptr
means - Take address of ptr
, look inside and assign its value (not address) to ptr3
If I understood your question correctly, you need to use pointers to pointers: ptr2
in my example instead of ptr3
If so, you can access elements like :
ptr2[0] = A
ptr2[1] = B
ptr2[2] = C
For the record the following will yeld the same results. Try it.
12 printf ("===>>> %x\n", ptr2);
13 printf ("===>>> %x\n", *ptr3);
Good discussion for your reference is here
If I did not misunderstand your question, this code should make a job
printf("TEST******************, %c\n", (*ptr2)[i]);
let me give an example,
char **str; // double pointer declaration
str = (char **)malloc(sizeof(char *)*2);
str[0]=(char *)"abcdefgh"; // or *str is also fine instead of str[0]
str[1]=(char *)"lmnopqrs";
while(*str!=NULL)
{
cout<<*str<<endl; // prints the string
str++;
}
free(str[0]);
free(str[1]);
free(str);
or one more best example which you can understand.
here i have used 2 for loops because i am iterating over each character of the array of strings.
char **str = (char **)malloc(sizeof(char *)*3); // it allocates 8*3=24 Bytes
str[0]=(char *)"hello"; // 5 bytes
str[1]=(char *)"world"; // 5 bytes
// totally 10 bytes used out of 24 bytes allocated
while(*str!=NULL) // this while loop is for iterating over strings
{
while(**str!=NULL) // this loop is for iterating characters of each string
{
cout<<**str;
}
cout<<endl;
str++;
}
free(str[0]);
free(str[1]);
free(str);