简体   繁体   中英

Memory allocation for struct using malloc where one of the data entries a pointer

I understand the difference between memory allocation using malloc for an array of struct and for an array of pointers to struct. But I want to assign memory using malloc for an array of struct, in the case that the struct itself contains a pointer to another struct. Here is the code for what I am trying to do:

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

typedef struct linkedlist {
    int pCol;
    struct linkedlist *next;
} plist;

typedef struct particle {
    int color;
    double rad;
    double rx;
    double ry;
    double vx;
    double vy;
    struct linkedlist *event;
} state;

int main()
{
    int N = 5, w = 4;

    plist *ls = (plist*)malloc((N+w)*sizeof(plist));
    printf("N=%d, w=%d, sizeof state=%d, total=%d, sizeof discs=%d\n\n",
    N,w,sizeof(plist), (N+w)*sizeof(plist), sizeof(ls));

    state *discs = (state*)malloc((N+w)*sizeof(state));
    printf("N=%d, w=%d, sizeof state=%d, total=%d, sizeof discs=%d\n",
    N,w,sizeof(state), (N+w)*sizeof(state), sizeof(discs));
    return 0;
}

When I run this, I get the following output:

N=5, w=4, sizeof plist=8, total=72, sizof ls=4

N=5, w=4, sizeof state=56, total=504, sizof discs=4

So, I want to know why does the ls or the discs get assigned only 4 bytes and how can I get total memory required assigned for these arrays of structs?

You are printing size of pointer(ls) and not size of datatype/structrure pointed by the pointer (*ls).

Do sizeof(*ls) and sizeof(*discs) in your printf statements if you intend to find size of plist and state because that is where ls and discs point to.

If you are thinking of printing the total size allocated to ls or discs by malloc. That is not possible. Its not going to print ((N+w)*sizeof(plist)) . So even doing sizeof(*ls) is not going to tell you how many plist structures you allocated

in your code, ls is of type plist * ,.ie, a pointer.

sizeof() is an operator which returns the size of the data type, not the amount of memory allocated.

Same goes for discs .

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