0

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;

1
  • Consider using a struct instead as that will make your program far more readable. Commented Dec 1, 2022 at 14:23

1 Answer 1

0

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, now I understand it much better!
@MatoušKovář If the problem is resolved then close th question by selecting the best answer and your reputation will be increased.:)

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.