Search code examples
cmultidimensional-arraypointer-to-array

How to use pointer to multi dimentional array in C language?


I have 2-D array

char arr[2][3]={"sam","ali"}

and pointer to this array

char(*ptr)[3]=arr;

How can I use this pointer to print arr[2][2] which in this case is i. I've tried * (*(ptr+1)+2) the same way I am dealing with the array but didn't work so can any one help and tell me how to deal with pointer to array in this case to print element [2][2].


Solution

  • This:

    char(*ptr)[3]=arr;
    

    isn't a pointer to a multi dimensional array, it's a pointer to one-dimensional array of size 3. But that's fine because a pointer can always also point to an array of the type it points to. So you have ptr point to an array of one-dimensional arrays of size 3. So far just for clarifying the terms.

    Your immediate problem are just wrong indices. Indices are based on 0, not 1, so with

    char arr[2][3]={"sam","ali"}
    

    valid indices for the first dimension of arr are just 0 and 1. The element you're looking for would be at ptr[1][2].


    With the pointer arithmetics notation in your question, you actually had the indices right, so I can't see where your problem was in this case. The following prints i as expected:

    #include <stdio.h>
    
    int main(void)
    {
        char arr[2][3]={"sam","ali"};
        char(*ptr)[3]=arr;
        printf("%c\n", *(*(ptr+1)+2));
    }
    

    Note this is completely equivalent to the more readable ptr[1][2].


    Side note: if you expected your elements to be strings -- they aren't, see haccks' answer for the explanation (a string must end with a '\0', your string literals do, but your array needs the room to hold it).