简体   繁体   中英

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;

}

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);
*d = malloc(count * sizeof(int));

然后

(*d)[i] = val

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM