1

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]);
    }
}
lea
  • 121
  • 4

2 Answers2

5

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);
axelduch
  • 10,769
  • 2
  • 31
  • 50
  • 1
    The first and last paragraphs are unnecessary. Your answer is correct. – Keith Thompson Mar 20 '15 at 16:14
  • When I write this it does not compile: invalid conversion from 'void*' to long int**' – lea Mar 20 '15 at 16:36
  • @lea You're compiling C as C++. Choose one. Because in C++ you *need* to cast the result of `malloc`, but in C you shouldn't cast it. In C `void*` is automatically converted to any other pointer type. – Emil Laine Mar 20 '15 at 16:39
  • Couldn't this be because `K` was not input correctly? What if you hard code `K` ? for instance `K = 1;` – axelduch Mar 20 '15 at 16:40
  • yes you're right. it compiled as a c file. but the input still stops in the internal loop... – lea Mar 20 '15 at 16:43
  • i don t understand what you mean aduch – lea Mar 20 '15 at 16:44
  • It might not be the problem, but what I was asking you to try, was to replace `scanf("%ld", &K);` by `K = 1;` – axelduch Mar 20 '15 at 16:45
  • i tried what you said for K=1000 (even if this is not the input the program must take) but it still does the same – lea Mar 20 '15 at 16:58
0

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
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157