简体   繁体   中英

How to access and modify pointer type variable declared inside a structure through a element of array containing pointers to the structure?

I declared a double pointer of the structure type and allocated it the required memory using calloc. Then I allocated data member (pointer) required space but it gave segmentation fault error. So only done1 gets printed. Can't we access data member pointers in structure like this?

I even replaced q[0] with *q but it didn't work.

#include<stdio.h>
#include<stdlib.h>

struct one
{
    int *a;
};

int main()
{
    struct one **q;
    q = (struct one**) calloc(sizeof(struct one*),10);
    printf("done1\n");
    q[0]->a = (int*) malloc(sizeof(int));
    printf("done2\n");
    *(q[0]->a) = 10;
    printf("done3 , q[0]->a stores %d value\n",*(q[0]->a));
    return 0;
}

Expected result would be printing of all the "done"'s but only first done is being printed.

You did a calloc so that you can create an array of pointers, ie {q[0], q[1], .., q[9]} . But, each individual element itself is a pointer and since you are doing calloc , they are probably initialized to NULL . But, then you are directly trying to access q[0]->a when q[0] is still pointer to NULL .

If you attach a debugger and see where it crashes, it will probably be the line q[0]->a = ...

First, you have to allocate memory to q[0] and then access q[0]->a .

#include <stdio.h>
#include <stdlib.h>

struct one
{
    int *a;
};

int main()
{
    struct one **q;
    q = (struct one**) calloc(sizeof(struct one*), 10);
    printf("done1\n");
    q[0] = (struct one*) calloc(sizeof(struct one), 1);
    q[0]->a = (int*) malloc(sizeof(int));
    printf("done2\n");
    *(q[0]->a) = 10;
    printf("done3 , q[0]->a stores %d value\n", *(q[0]->a));
    return 0;
}

BTW, your code wasn't compiling on my compiler saying unknown type one** . So I changed it with struct one everywhere.

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