0

有人可以告诉我该代码有什么问题吗?我不能使用 malloc,因为我没有在课堂上学习它。我的意思是我可以在没有 malloc 的情况下制作一个二维字符串数组,如果可以,我应该如何在我想要的时候编写一个元素更改/打印/扫描。在此先感谢

int main() {

    size_t x,y;
    char *a[50][7];

    for(x=0;x<=SIZEX;x++)
    {
        printf("\nPlease enter the name of the new user\n");
        scanf(" %s",a[x][0]);

        printf("Please enter the surname of the new user\n");
        scanf(" %s",a[x][1]);

        printf("Please enter the Identity Number of the new user\n");
        scanf(" %s",a[x][2]);

        printf("Please enter the year of birth of the new user\n");
        scanf(" %s",a[x][3]);

        printf("Please enter the username of the new user\n");
        scanf(" %s",a[x][4]);

    }

    return 0;
}
4

2 回答 2

2

因此,您需要一个二维字符串数组(字符数组)。实现此目的的一种方法是将 char 的 3d 数组分配为:

char x[50][7][MAX_LENGTH];

你可以认为有一个数组开始(指针)矩阵,然后是另一个维度来为你的矩阵提供深度(即你的字符串的存储空间)。

只要您愿意malloc为字符串手动分配使用或类似的存储空间,您的方法也很好。

于 2016-01-04T18:39:10.030 回答
0

我可以制作一个没有malloc的二维字符串数组吗

当然。让我们把它减少到 2*3:

#include <stdio.h>

char * pa[2][3] = {
   {"a", "bb","ccc"},
   {"dddd", "eeeee", "ffffff"}
  };

int main(void)
{
  for (size_t i = 0; i < 2; ++i)
  {
    for (size_t j = 0; j < 3; ++j)
    {
      printf("i=%zu, j=%zu: string='%s'\n", i, j, pa[i][j]);
    }
  }
}

输出:

i=0, j=0: string='a'
i=0 j=1: string='bb'
i=0, j=2: string='ccc'
i=1, j=0: string='dddd'
i=1, j=1: string='eeeee'
i=1, j=2: string='ffffff'
于 2016-01-05T18:11:22.493 回答