0

I have an array of chars, and it is initialized using a nested for loop.

How do I access each element of the array such as a[i][j] using a char pointer?

I have tried * (* (p+i)+j) which gives me a unary error. I have also tried the following:

char a[maxr][maxc];
char *p = 0;
p = &a[0][0];
int i,j;
for (i = 0; i < r-1; i++){
    for (j = 0; j < c-2; j++){
         while (*p != '\0'){
               *p = 'Y';
               p++;
         }
    }
}

If i do:

char a[maxr][maxc];
    char *p = 0;
    p = &a[0][0];
    int i,j;
    for (i = 0; i < r-1; i++){
          p = p+i;  
        for (j = 0; j < c-2; j++){
            p = p+j;
             while (*p != '\0'){
                   *p = 'Y';
                   p++;
             }
        }
    }

This seems to traverse the array; however, I am not quite sure if it is the correct way to do it.

  • Without knowing the type of `a` this is not possible to answer accurately. An array of arrays vs an array of pointers will have different answers. Update the question to include the declaration of `a` please. – WhozCraig Feb 05 '15 at 14:39
  • possible duplicate of [Pointing at array](http://stackoverflow.com/questions/7613584/pointing-at-array) – Werner Henze Feb 05 '15 at 14:45
  • @WhozCraig `a` is there ... The markdown was failing but I fixed it. – unwind Feb 05 '15 at 14:52

2 Answers2

1

Assuming a is defined as char *a[m] (m > i)

To get the value of a[i][j], you've got to use something like,

char ** p = a;

and

*(*(p + i) + j)

provided, i and j a are valid index locations.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

with r is total row, try this:

*(p+i*r +j)
Hu Go
  • 1
  • 1