我知道这个问题已被问及here,here和here以及更多次,但有些问题尚未解决。我想在C中制作一个卡诺图解算器,我希望我的一个函数将2D数组传递回主函数,所以这是我的程序:
typedef char (*arr)[][4];
int rows;
int main(void){
int noVar;
char *grid;
printf("Please Enter the number of variables: ");
scanf("%d",&noVar);
grid = setMap(noVar);
feedOnes(grid);
}
arr setMap(int noVar){
rows = pow(2,noVar)/4;
char grid[rows][4];
for(int i = 0; i<rows; i++){
for(int j = 0; j<4; j++){
grid[i][j]='0';
}
}
printGrid(grid);
return &grid;
}
这使我在现在完成工作时发出4次警告:
In file included from kmap.c:9:
./setMap.h:33:13: warning: address of stack memory associated with local
variable 'grid' returned [-Wreturn-stack-address]
return &grid;
^~~~
./setMap.h:56:1: warning: control reaches end of non-void function
[-Wreturn-type]
}
^
kmap.c:16:8: warning: incompatible pointer types assigning to 'char *' from
'arr' (aka 'char (*)[][4]') [-Wincompatible-pointer-types]
grid = setMap(noVar);
^ ~~~~~~~~~~~~~
kmap.c:17:12: warning: incompatible pointer types passing 'char *' to parameter
of type 'char (*)[4]' [-Wincompatible-pointer-types]
feedOnes(grid);
^~~~
./setMap.h:36:19: note: passing argument to parameter 'grid' here
int feedOnes(char grid[][4]){
^
我的问题是,我可以解决这些警告吗?这些警告将来会引起任何问题,因为我不知道他们为什么会出现
另外,我是新手,所以如果没有正确地提出这个问题,请不要对我苛刻..
谢谢。
答案 0 :(得分:0)
数组grid[][]
是setMap()
函数的本地数组。此函数返回后,该变量不再可用且超出范围。 本地变量在堆栈内存上声明。
要使这样的内容有效,您需要使用malloc()
从堆中分配和取消分配内存和free()
函数调用。
请参阅此链接以了解堆栈与堆内存:
What and where are the stack and heap?
请参阅此链接,了解在C中确定范围:
https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm
快乐编程!