lea
lea

Reputation: 121

What is wrong with my malloc declaration?

I have written the following code. The thing is that when it enters the internal loop the program stacks and so the input procedure stops. Have I done something wrong?

What I do here is create an array of pointers, and each pointer points to an array - each array of different size. Then the even numbered lines take only one number, while the odd numbered lines take more.

long int K,i,j; 
scanf("%ld", &K);   

long int **pl_r;
pl_r = (long int **) malloc(2*K*sizeof(long int *));              

for(i=0; i<K; i++)
{
    pl_r[2*i] = (long int *) malloc(1 *sizeof(long int));
    scanf("%ld", &pl_r[2*i][0]);
    pl_r[2*i+1] = (long int *) malloc(pl_r[2*i][0] *sizeof(long int));
    scanf("%ld", &pl_r[2*i+1][0]);
    for(j=1; j<pl_r[2*i][0]-1; i++){
        scanf("%ld", &pl_r[2*i+1][j]);
    }
}

Upvotes: 1

Views: 117

Answers (2)

Emil Laine
Emil Laine

Reputation: 42828

First of all, don't cast the result of malloc. As for the question, the first malloc should be:

pl_r = malloc(K*sizeof(long int *))
                                ^ this is missing

Upvotes: 0

axelduch
axelduch

Reputation: 10849

Make sure you have included <stdlib.h> to avoid any warning when you don't cast with malloc, because you should not cast with malloc if I'm not mistaken.

Then to avoid confusion between pointers and pointers of pointers when allocating memory you can do this

pl_r = malloc(K * sizeof *pl_r);

Upvotes: 5

Related Questions