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.

3
  • 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. Commented Feb 5, 2015 at 14:39
  • possible duplicate of Pointing at array Commented Feb 5, 2015 at 14:45
  • @WhozCraig a is there ... The markdown was failing but I fixed it. Commented Feb 5, 2015 at 14:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

with r is total row, try this:

*(p+i*r +j)

Comments