0

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?

Gene
  • 561
  • 3
  • 9
  • 19
  • 1
    Just a FYI: the `&c` is a value of type `char (*)[4]` (pointer to array of 4 characters): `c` does not decay to a pointer to its first element in the expression `ptr = &c;`. Your compiler should have warned about incompatible types in the assignment ... – pmg Jul 10 '11 at 15:13

4 Answers4

5

Suppose:

  6   char c[] = "ABC";
  7 
  8   char *ptr   = &c;
  9   char *ptr2  = ptr;       
 10   char **ptr3 = &ptr;   

enter image description here

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

Community
  • 1
  • 1
James Raitsev
  • 82,013
  • 132
  • 311
  • 454
3

For your example:

int i;
for(i=0; i<3; i++){
    printf("TEST******************, %c\n", (*ptr2)[i]);
}
Oliver Charlesworth
  • 252,669
  • 29
  • 530
  • 650
1

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);
Abhishek D K
  • 1,272
  • 9
  • 21
1

If I did not misunderstand your question, this code should make a job

printf("TEST******************, %c\n", (*ptr2)[i]);
eugene_che
  • 1,967
  • 10
  • 11