简体   繁体   中英

Pointing to an array inside a struct that is inside another struct

How can I access an array / other type of data that is inside of a struct which is inside of another struct. This is what Ive tried so far and its coming out as c is not declared. I know I can declare c as prod_t *c but it defeats the purpose of something Im trying to do as it doesnt exist inside of the root ( a_t struc).

typedef struct {
    char *name;
} prod_t;

typedef struct {
    prod_t *c;
} a_t;



int
main(int agrc, char **argv){
    a_t *root = malloc(sizeof(a_t));
    root->c=malloc(sizeof(prod_t));

    c->name = malloc( 5 * sizeof(char));
    strcpy(c->name, "abc");

    printf("%s",root.c->name);



    return 0;
}

In your code, c->name is not a valid variable name. c is a member variable of the structure variable root . There is no standalone variable named c .

You can use like

root->c->name = malloc( 5 );

and

strcpy(root->c->name, "abc");

and

printf("%s\n", root->c->name);

Also, remember,

  1. sizeof(char) is guranteed to produce 1 in C , so you can drop that part.
  2. Once you're done using the allocated memory, you need to free() them.

You have three pointers one is "enclosed" in another. So you have to write

root->c->name = malloc( 5 * sizeof(char));
strcpy( root->c->name, "abc");

printf("%s",root->c->name);

And you have to free them in the following order

free( root->c->name );
free( root->c );
free( root );

Take into account that in general you have to check whether the "outer" pointer was successfully "allocated" before allocating memory pointed to by the "inner" pointer.

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