简体   繁体   English

C中没有malloc的字符串数组

[英]Array of strings with no malloc in c

Can someone tell me whats wrong with that code?And i cant use malloc because i havent learn it in class.I mean can i make a 2d array of strings without malloc and if yes how i am i supposed to write an element when i want to change it/print it/scan it.Thanks in advance 有人可以告诉我该代码有什么问题吗?我不能使用malloc,因为我没有在课堂上学习它。我的意思是我可以在没有malloc的情况下制作2D字符串数组,如果是的话,我应该如何编写一个元素进行更改/打印/扫描。

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;
}

So, you need a 2d array of strings (char arrays). 因此,您需要一个二维的字符串数组(char数组)。 One way to achieve this would be to allocate a 3d array of char as: 实现此目的的一种方法是将3d char数组分配为:

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

You can think as having a matrix of array start (of pointers) and then, another dimension to give depth to your matrix (ie storage space for your string). 您可以考虑将矩阵的起始数组(指针)和另一个维数赋予矩阵深度(即字符串的存储空间)。

Your approach is also fine, as long as you are willing to allocate manually using malloc or similar storage space for your strings. 只要您愿意使用malloc或类似的存储空间为字符串手动分配,您的方法也很好。

can i make a 2d array of strings without malloc 我可以在没有malloc的情况下制作2D字符串数组吗

Sure. 当然。 Let's reduce this to 2*3: 让我们将其减少为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]);
    }
  }
}

Output: 输出:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM