0

I have a program

#include <stdio.h>
int main()
{
    int i , j;
    char *str[2][3] = {{"john", "alice", "bobby"},
                       {"peter", "mark", "anthony"}};
    char (*ptr)[3] = str;  //Compiler throws Warning here 
    for ( i = 0 ; i < 2 ; i++)
    {
        for ( j = 0 ; j < 3; j++)
        {
            printf("%s ", str[i][j]); //This works fine.
            printf("%s ", ptr[i][j]); //segmentation fault here
        }
    }
}

My intension is to use a pointer to a two dimensional array of pointers. However the compiler throws error as follows;

test.c: In function ‘main’:
test.c:7:19: warning: initialization from incompatible pointer type [enabled by default]
 char (*ptr)[3] = str;
                   ^

Also, I am getting segmentation fault while running. My question is how would I have a pointer which points to a two dimensional array of pointers?

2
  • What exactly do you want to achieve? As the compiler says the types are incorrect, so you’ll need to make them equal. Why can’t you use the same type, that is *[2][3]? Commented Nov 21, 2020 at 14:44
  • @Sami Kuhmonen, I am trying to learn and figure out the usage of a pointer to a multidimensional array. I know I can print directly using printf("%s ", str[i][j]) which I did in my above program . But I would like to use pointer to a multidimensional array. Commented Nov 21, 2020 at 14:47

2 Answers 2

1

char (*ptr)[3] = str; This sentence attempts to assign an address to a char variable. char *(*ptr)[3] = str; should be what you want.

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

Comments

0

Consider first the multidimensional-array part in isolation. Given ...

typedef /* ... some type ... */ foo;
foo arr[2][3];

... the pointer type to which arr decays is foo (*)[3]:

foo (*ap)[3] = arr;

Now, if type foo were defined as char * to yield an analogue of the case presented in the question:

typedef char *foo;

then the above declaration of ap would be equivalent to

char *(*ap)[3] = arr;

That is, the type you want is char *(*)[3], not char (*)[3].

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.