我必须用动态2d数组编写一个程序,但是我遇到了问题。一切正常,直到我尝试打印超过4行的数组。最多4行看起来都很好,但是对于第5行,最后一行的长度扩展为7631472
,这会导致分段错误。
谢谢你们回复,我做了你们建议我的事。但是我发现问题出在其他地方,它的长度和#34;阵列。每当我添加mroe而不是这4个项目时,它就开始从内存中填充一些随机值。
代码:
#include <stdio.h>
#include <stdlib.h>
int addRow(int i, int **array2d, int * lengths) {
int len, value;
int counter;
i++;
scanf("%d", &len); /*write the length of each row*/
*(array2d + i-1) = malloc(sizeof (int) * len);
*(lengths + i-1) = len;
for(counter = 0; counter < len; counter++) {
scanf("%d", &value); /*write each element in row*/
*(*(array2d+i-1)+counter) = value;
}
return i;
}
void print(int *i, int **array2d, int * lengths) {
int counter, counter2;
for(counter = 0; counter < *i; counter++) {
for(counter2 = 0; counter2 < *(lengths+counter); counter2++) {
printf("%d ",*(*(array2d+counter)+counter2));
}
printf("\n");
}
}
void end(int *i, int **array2d, int * lengths, char * word) {
int counter;
for(counter = 0; counter < *i; counter++)
free(*(array2d + counter));
free(array2d);
free(lengths);
free(word);
}
int main() {
int ** array2d = (int**) malloc (0*sizeof(int*));
int * lengths = (int*) malloc (0*sizeof(int)); /*length of each row*/
char * word = (char*) malloc (3*sizeof(char));
int i, isEqual; /* i - number of rows */
i = 0;
while(1) {
scanf("%s", word);
isEqual = strcmp(word, "add");
if(!isEqual)
i = addRow(i, array2d, lengths);
isEqual = strcmp(word, "print");
if(!isEqual)
print(&i, array2d, lengths);
isEqual = strcmp(word, "end");
if(!isEqual) {
end(&i, array2d, lengths, word);
return 0;
}
}
return 0;
}
答案 0 :(得分:2)
在main中,如果我们读取malloc:
的人,则分配大小为0的数组 The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
这意味着您创建了一个未定义的行为,因此它可以适用于所有情况,因为它永远无法工作。
除此之外,您应该分配大小为1的数组,然后在需要时使用realloc
增加大小。
答案 1 :(得分:0)
您应首先分配array2d以分配* array2d。
第二个指针* array2d指向将包含您键入的数据的第一个新行单元格。 但首先,您必须为您键入的数据行列表分配一个新项目:
array2d = (int**) realloc(array2d, i)
试试这个:
int addRow(int i, int **array2d, int * lengths) {
int len, value;
int counter;
i++;
array2d = (int**) realloc(array2d, sizeof (int*) * i); //<<== realloc adding a new list item
scanf("%d", &len); /*write the length of each row*/
*(array2d + i-1) = malloc(sizeof (int) * len);
*(lengths + i-1) = len;
for(counter = 0; counter < len; counter++) {
scanf("%d", &value); /*write each element in row*/
*(*(array2d+i-1)+counter) = value;
}
return i;
}