I'm trying to learn how to allocate a 2d array within a struct, but it keeps getting a segfault. I know how to allocate a 2d array outside of a struct but i don't know why its getting a segfault when i move it into a struct.
/*program to allocate a 2d array and fill it with 0's and then print it.*/
#include<stdio.h>
#include<stdlib.h>
typedef struct stuff
{
int **arr;
}stuff;
int main()
{
stuff x;
int i,j;//loop counters
//allocate 2d array
x.arr = (int**)malloc(sizeof(int*)*4);
for(i=0; i<4; i++)
x.arr[i] = (int*)malloc(sizeof(int)*4);
//intialize 2d array to 0
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
x.arr[i][j] = 0;
//print 2d array
for(i=0; i<4; i++);
for(j=0; j< 4; j++)
printf("arr[%d][%d] = %d \n", i ,j ,x.arr[i][j]);
return 0;
}
You have an extra semicolon in your last i
loop. This causes you access wrong memory address, as j
loop runs with i
value of 4, which is out of bounds.
Change for(i=0; i<4; i++);
into for(i=0; i<4; i++)
and everything works well
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.