C语言 如何创建指向二维字符数组的指针?

yhived7q  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(145)

我在声明指向字符的二维变量的指针时遇到了问题...

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;

这是我的代码。我得到的错误是错误:无法使用类型为'const char [9][2]'的左值初始化类型为'char()[2]'的变量。发生了什么情况?我如何修复它?谢谢大家。char(* ptr)[2] = d1;

xmjla07d

xmjla07d1#

您声明了一个二维数组,如

const char * d1 [][2]

数组元素的类型为const char *[2]
因此,指向数组第一个元素的指针声明如下所示:

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

用作初始化器的数组d1被隐式转换为指向其第一个元素的指针。
使用指针算法可以访问原始数组的任何元素。
这是一个演示程序。

#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' );
    }
}

程序输出为

"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"

相关问题