c-双动态阵列



这是我第一次使用动态数组,我真的很困惑。我的原始数组(如下(运行良好。

#include <stdio.h>
int main()
{
char icdC[4][10];
for(int i =0;i<4;i++){
for(int j=0;j<10;j++){
printf("What are your ICD codes [%d][%d]n",i,j);
scanf("%s", &icdC[i][j]);
}
}
return 0;
}

然而,我尝试将这个数组转换为双动态数组(如下(,它似乎不能正确工作,因为它会告诉我";信号:分段故障(核心转储(,否则就无法运行。

#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char** icdC;
icdC = (char**)malloc(4*10*sizeof(char));

for(int i=0;i<4;i++){
for(int j=0;j<10;j++){
printf("What are your ICD codes [%d][%d]n",i,j);
scanf("%s", &icdC[i][j]);
}
}
return 0;
}

问题似乎位于icdC = (char**)malloc(4*10*sizeof(char));中,因为它对您试图创建的第二个数组的引用不正确。

在C中,有许多表示2d数组的选项,其中创建一个指针数组,每个指针指向一个特定的行。然后,您可以使用malloc为每个阵列分配内存,这允许您生成一个";指针数组";。

实施方式很可能是:

char ** icdC;
int r = 4, c = 10;
icdC = (char*) malloc(sizeof(char*) * r);
for (int i = 0; i < r; i++) {
icdC[i] = malloc(sizeof(char) * c);
}

注意:您也可以像上面所做的那样,在两个循环中完成此实现。

从这里,您可以执行嵌套循环来扫描值,就像您在代码片段中所做的那样。请记住,现在您可以通过指示相应行和列的索引来访问值,如下所示:icdC[row_num][row_column] = ....

一开始可能看起来很奇怪,但当你掌握了这个概念后,一切都很好,很有趣!

最新更新