【问题标题】:why use * to define string array?为什么使用 * 来定义字符串数组?
【发布时间】:2021-11-20 08:05:53
【问题描述】:

为什么我们这里需要*names[]而不是names[],当我将它定义为const char names[]时,它不会执行。

#include <stdio.h>
#include <stdlib.h>
const int MAX = 4;
int main()
{
  const char *names[] = {
                 "dggg",
                 "ggq",
                 "gg2",
                 "g23",
   };


   for ( int i = 0; i < MAX; i++)
   {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   return 0;
}

【问题讨论】:

  • 您想要一个指向字符串的指针数组还是只包含一个字符串的数组?如果没有*,您只能存储 1 个字符串。
  • names 是一个由 (4) 个指针组成的数组。每个指针都指向一个const char,它通常被解释为一个字符串
  • 整数数组不需要*: int arr[] = { 1, 2, 42, -1};;指向 int 的 指针 数组可以:int *ap[] = { NULL, NULL, &amp;errno, NULL }; ... char 数组不需要 *char a[] = {'q', 'u', 'u', 'x'};(请注意,此数组不是字符串)
  • 大多数时候,*等于[],可以把字符串当成特殊数组。在您的代码中, *names[] 是二维数组。
  • @Ace_of_King 不,它不是二维数组,而是一维指针数组。每个指针可以指向单个字符,不一定是指向字符数组第一个字符的指针。一个真正的二维数组是char names[][];

标签: c pointers syntax


【解决方案1】:

C 中的字符串是一个 = 一维字符数组。比如

const char string[3] = "abc";

示例代码有一个 C 字符串数组,即

{dggg", "ggq",....}

没有指针的情况,就像

#include <stdio.h>
#include <stdlib.h>
//const int MAX = 4;

#define NUMBER_OF_STRING 4
#define MAX_STRING_SIZE 40

int main()
{

  const char names[NUMBER_OF_STRING][MAX_STRING_SIZE] = {
                 "dggg",
                 "ggq",
                 "gg2",
                 "g23",
   };


   for ( int i = 0; i < NUMBER_OF_STRING; i++)
   {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   return 0;
}

【讨论】:

  • 您的string 元素太小,您忘记了最后的'\0',在您的完整示例中也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多