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?
lsanddiscsare of pointer type, which has size of 4bytes on 32-bit systems.