Home > Software design >  How to create pointer to 2d array of chars?
How to create pointer to 2d array of chars?

Time:12-04

I am having trouble declaring pointer to 2d variable of chars...

    const char * d1 [][2] =
  {
    { "murderer", "termination specialist" },
    { "failure", "non-traditional success" },
    { "specialist", "person with certified level of knowledge" },
    { "dumb", "cerebrally challenged" },
    { "teacher", "voluntary knowledge conveyor" },
    { "evil", "nicenest deprived" },
    { "incorrect answer", "alternative answer" },
    { "student", "client" },
    { NULL, NULL }
  };
  char ( * ptr ) [2] = d1;

That is my code. Error I am getting is error: cannot initialize a variable of type 'char (*)[2]' with an lvalue of type 'const char *[9][2]' What is happening and how can I fix it? Thanks everyone. char ( * ptr ) [2] = d1;

CodePudding user response:

You declared a two-dimensional array like

const char * d1 [][2]

Elements of the array have the type const char *[2].

So a declaration of a pointer to the first element of the array will look like

const char * ( * ptr ) [2] = d1;

The array d1 used as an initializer is implicitly converted to pointer to its first element.

Using the pointer arithmetic you can access any element of the original array.

Here is a demonstration program.

#include <stdio.h>

int main( void )
{
    const char *d1[][2] =
    {
      { "murderer", "termination specialist" },
      { "failure", "non-traditional success" },
      { "specialist", "person with certified level of knowledge" },
      { "dumb", "cerebrally challenged" },
      { "teacher", "voluntary knowledge conveyor" },
      { "evil", "nicenest deprived" },
      { "incorrect answer", "alternative answer" },
      { "student", "client" },
      { NULL, NULL }
    };
    const size_t N = sizeof( d1 ) / sizeof( *d1 );
    const char * ( *ptr )[2] = d1;

    for (size_t i = 0; i < N && ptr[i][0] != NULL; i  )
    {
        for (size_t j = 0; j < 2; j  )
        {
            printf( "\"%s\" ", ptr[i][j] );
        }
        putchar( '\n' );
    }
}

The program output is

"murderer" "termination specialist"
"failure" "non-traditional success"
"specialist" "person with certified level of knowledge"
"dumb" "cerebrally challenged"
"teacher" "voluntary knowledge conveyor"
"evil" "nicenest deprived"
"incorrect answer" "alternative answer"
"student" "client"
  • Related