AdamTopi
AdamTopi

Reputation: 63

C array of pointers and malloc

I'm trying to get data from std stored into an array, using pointers. The main declares d as int *d; and the function is called using x = getdata(&d); When I step through it with gdb it dies at the first iteration of the for loop, when it tries *d[i]=val;

int getdata(int **d)
{ 
    int count,val,i,j=0; 

    scanf("%d", &count);

    d = malloc(sizeof *d * count);
    for( i = 0; i < count-1; i++) {

    scanf("%d",val);

    *d[i]=val;  

    }

    for ( i = 0; i < count; i++)
            printf("Number %d\n",*d[i]);

    return count;

}

Upvotes: 3

Views: 1025

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

The memory should be allocated as follows

*d = malloc(count * sizeof **d);

The values should be accessed as follows

(*d)[i] = val;

It is also not clear why you allocate count elements and only initialize count - 1 elements in the input cycle (and later print all count elements in output cycle).

Upvotes: 2

Mel Nicholson
Mel Nicholson

Reputation: 3225

What you have is a pointer to an array, not an array of pointers.

1) malloc returns a void* so you need to assign the result to *d instead of d

2) the data size you want is of an int, not an int* (using *d gets you an int* where **d is an int)

*d = malloc(sizeof(**d) * count);

3) Indexing the array requires slightly different syntax

(*d)[i] = val;

printf("%d\n", (*d)[i]);

4) The second scanf needs a pointer, not an int

scanf("%d", &val);

Upvotes: 2

Pavan Yalamanchili
Pavan Yalamanchili

Reputation: 12109

*d = malloc(count * sizeof(int));

then

(*d)[i] = val

Upvotes: 2

Related Questions