New_Bee
New_Bee

Reputation: 81

Making a two dimensional array at run time using malloc

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;
}

Upvotes: 0

Views: 86

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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().

Upvotes: 1

Spikatrix
Spikatrix

Reputation: 20244

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));

and don't cast the result of malloc.

Upvotes: 2

Related Questions