3

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].

3
  • Avoid multi-dimensional arrays in C. Consider using flexible array members to implement your own matrix abstract data type, like here Commented Aug 16, 2017 at 6:58
  • 2
    Be careful when using strings and fixed-sized arrays, you have to remember that a string of three characters really need space for four characters, to include the terminating null character '\0'. Commented Aug 16, 2017 at 6:58
  • 1
    Note that "sam" actually requires 4 bytes, as it includes the string termination character Commented Aug 16, 2017 at 6:59

2 Answers 2

8

You should not print arr[2][2] because you are accessing array out of bounds. Also note that there is no space for '\0' character to be stored in in the given array.

char arr[2][4] = {"sam","ali"}  
char(*ptr)[4] = arr;

Using ptr you can access the elements of arr as ptr[1][2].

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

Comments

4

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.