简体   繁体   中英

Initializing a struct and a pointer

So I know how to declare a struct described as such:

struct type_t {
    int ha;
    int ja;
    int ka;
};

Then to initialise it:

struct type_t[10];

How about when I am faced with such a structure:

struct type_t {
    int ha;
    int ja;
    int ka;
} *type_tlist = NULL;

Would I go ahead and just use *type_tlist in my main code?

Thanks in advance guys!!

Let's say we have this struct:

struct type_t {
    int ha;
    int ja;
    int ka; };

This is the definition of struct type_t .

You can declare variables of type struct type_t as follows:

struct type_t a;

Or arrays:

struct type_t b[10];

Those 2 constructs declares some variables that you can use right away. You can declare pointers having struct type_t as a type:

struct type_t *c;

but in order to access members from them, you need to allocate some memory for them:

struct type_t *c = malloc(sizeof(struct type_t));

Note that when having a variable (like a or b[2]), you access its members using the dot operator:

a.ha = 3;

for example. But when having a pointer, you access its members using -> operator:

c -> ha = 3;

You may assign NULL value to a pointer:

c = NULL;

but you may not access its members until you allocate some memory for it.

I tried to give you a glimpse about working with structs but I would suggest you reading a C book (or at least the chapter about structs and/or pointers).

should be:

struct type_t {
        int ha;
        int ja;
        int ka;
};

typedef type_t* type_tlist;

you can then initialize a pointer to the struct like this.

type_tlist x = malloc(sizeof(type_t));

if you don't want to use typedef, you can do it like this.

struct type_t* x = malloc(sizeof(type_t));

now for using the elements of the struct

you can use either -> operator or complicate it by using the . operator the ff. code does the same thing.

x -> ha = 1;
(*x).ha = 1; 

note that these equivalent:

array[0] == *(array + 0) 

so you dont need to use the -> operator if the struct is in an array. you can use the dot without the reference operator '*'

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