I have been trying to allocate a 2 dimensional array at run time using malloc by using the concept of pointers to pointers. This code doesn't show any compilation error but gives a runtime error.
#include<stdio.h>
#include<stdlib.h>
int ** alpha(void)
{
int **x;
x=(int **)malloc(3*sizeof(int *));
for(int i=0;i<3;i++)
{
x[0]=(int *)malloc(3*sizeof(int));
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
x[i][j]=i+j;
}
}
return x;
}
int main()
{
int **p;
p=alpha();
printf("%d",p[1][2]);
return 0;
}
Spikatrix
20.3k7 gold badges44 silver badges85 bronze badges
-
There's a difference in C between a two-dimensional array and an array-of-arrays, btw. This is the latter.Alex Celeste– Alex Celeste2015年01月14日 14:07:35 +00:00Commented Jan 14, 2015 at 14:07
-
And the run time error is..?AndersNS– AndersNS2015年01月14日 14:24:36 +00:00Commented Jan 14, 2015 at 14:24
2 Answers 2
The reason for the runtime error is because you allocate memory just for x[0].So, change
x[0]=(int *)malloc(3*sizeof(int));
to
x[i]=malloc(3*sizeof(int));
answered Jan 14, 2015 at 14:06
Spikatrix
20.3k7 gold badges44 silver badges85 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
In
x[0]=(int *)malloc(3*sizeof(int));
you ended up allocating memory for only index 0 three times. use i.
After you're done using , don't forget to free() the allocated memory. Otherwise, it'll result in a memory leak.
Also, no need to cast the return value of malloc()/calloc().
answered Jan 14, 2015 at 14:07
Sourav Ghosh
135k17 gold badges192 silver badges271 bronze badges
Comments
lang-c