【发布时间】:2018-01-12 18:23:16
【问题描述】:
我想知道是否可以在 c 中声明一个二维数组,即使我们不知道大小。我试过这样做
char **array; //2D array of characters - global
int length, height; // - global
然后在函数中像这样声明大小
void size_and_data(){
int i;
//some more code here
array=(char**)malloc(sizeof(char*)*height); //height and length are
//given from a file
for(i=0;i<length; i++)
array[i]= (char*)malloc(sizeof(char)*length);
//more code to follow..
}
同样在这一点上,我的数组充满了字符,我打印了每一个字符以确保它们被正确存储。但是,如果我在另一个函数中尝试访问元素,我会遇到分段错误。这就是我尝试访问它们的方式:
void access_f(){
int i,j;
for(i=0; i<height;i++){
for (j=0;j<length; j++)
printf("%c", array[i][j]);
}
}
请记住,两者之间不再涉及任何函数,因此数组不会以任何方式发生变化。这应该发生吗?我认为全局变量会保持它们的值,直到程序停止运行。
我是 c 新手,任何帮助将不胜感激!
谢谢!
【问题讨论】:
-
@user3121023 你是对的。尺寸混淆了..
-
@EugeneSh。尺寸没有混淆。更改为
printf("%c", *(arr+i) + j);以使其工作。 -
@felix 他们搞混了。第一次分配
height指针的 if,但迭代length元素。 -
@EugeneSh。我站得更正了。如果按照我的方式调用 printf 似乎不会介意访问范围之外的元素。 malloc 或 array[i] 的分配也不会抛出任何东西。
标签: c arrays dynamic-memory-allocation