0

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;
}
2
  • There's a difference in C between a two-dimensional array and an array-of-arrays, btw. This is the latter. Commented Jan 14, 2015 at 14:07
  • And the run time error is..? Commented Jan 14, 2015 at 14:24

2 Answers 2

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

and don't cast the result of malloc.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.