I know this question has been asked here , here and here and many more times, but something's not working yet. I am trying to make a karnaugh map solver in C and I want one of my functions to pass a 2D array back to the main function, so here is my program:
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;
}
This gives me an 4 warnings while it does the job for now:
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]){
^
My question is, can I resolve these warnings? and will these warnings cause any problem in future as I do not know why are they appearing
Also, I am a newbie so please don't be harsh at me if this question was not asked properly..
Thank You.
The array grid[][]
is local to the setMap()
function. Once this function returns, the variable is no longer available and is out-of-scope. Local variables are declared on the stack memory .
In order for something like this to work you will need to allocate and deallocate memory from the heap using the malloc()
and free()
function calls respectively.
Refer to this link for clarification on Stack vs Heap Memory:
What and where are the stack and heap?
Refer to this link for scoping in C :
https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm
Happy Programming!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.