如何在C中动态初始化2D数组?

时间:2018-06-10 22:02:13

标签: c arrays

所以,我正在用C编写一个程序。我要做两部分。一部分涉及一维数组,另一部分涉及二维数组。程序要求是我们通过用户输入输入数组的大小。 以下是我为第一个做的事情:

char* i; 
printf("\n\nHow many characters? ");  //takes input from user
scanf("%d",&num);
i = new char[num];

这很有用。

现在,当我对2D阵列执行相同操作时,它不起作用。怎么做?

char* i; 
int numOfStrings,maxSize;       
printf("How many strings do you want to enter? ");
scanf("%d",&numOfStrings);
printf("What is the max size of the strings? ");
scanf("%d",&maxSize);

i = new char[numOfStrings][maxSize];    

1 个答案:

答案 0 :(得分:3)

如果数字相当小,您可以使用C99数组定义:

.element.html()

2D数组相同:

printf("\n\nHow many characters? ");  //takes input from user
if (scanf("%d", &num) != 1)
    return 1;
char i[num];

但请注意,int numOfStrings, maxSize; printf("How many strings do you want to enter? "); if (scanf("%d", &numOfStrings) != 1) return 1; printf("What is the max size of the strings? "); if (scanf("%d", &maxSize) != 1) return 1; char i[numOfStrings][maxSize]; 是一个非常令人困惑的数组名称,更不用说2D数组了。