0

I created a structure with 3 integer members and a pointer variable ptr

 ptr=(struct node*)calloc(15,sizeof(struct node*));
  printf("%ld",sizeof(ptr));

however using the sizeof operator to get the size of ptr is printing a size less than 15(i.e. 8). What should be done to just get the size of the pointer variable if this is incorrect.

  • 4
    It *is* returning the size of the pointer: a pointer on your system is 8 bytes, regardless of what it points to. What you want is the allocated size of the buffer that the pointer points to, and C doesn't give you a way to query that; you have to keep track for yourself how much memory you allocated. – Nate Eldredge Dec 24 '20 at 19:36
  • Sizeof returns the numbers of bytes, it doesn't work as you think. – Matteo Pinna Dec 24 '20 at 19:37
  • 4
    By the way, passing `sizeof(struct node *)` to `calloc` is almost certainly a mistake; if `ptr` is to point to an array of `struct node`s, then you want space for 15 `struct`s, not 15 pointers. You should have `sizeof(struct node)` there instead. – Nate Eldredge Dec 24 '20 at 19:38
  • 1
    Even better would be `ptr=calloc(15,sizeof(*ptr));` – 12431234123412341234123 Dec 24 '20 at 19:43
  • Best to use specifier `"%zu"`, not `"%ld"`, when printing the result of `sizeof` – chux - Reinstate Monica Dec 24 '20 at 21:51

2 Answers2

2

The result you have obtained is totally as expected.
Indeed, sizeof(ptr) returns the size of a pointer, which depends on your processor architecture (As it returns 8 you are very likely on a 64-bit processor).

cocool97
  • 1,201
  • 1
  • 10
  • 22
0

The size of a pointer will depend on your hardware... A pointer stores an address in memory that represents the beggining of that thing you are allocating. It doesn't how matter how big that thing is: It's initial address will have the same number of bytes as any other variable.

The line ptr=(struct node*)calloc(15,sizeof(struct node*)); is allocating space for 15 pointers, not 15 structs, you probably want to remove the * in the sizeof.

After you fix that, you can add the two lines to see the difference:

printf("size of a pointer to node* is: %d\n", sizeof(ptr));
printf("size of a struct pointed by a node* is :%d\n", sizeof(*ptr));
vmp
  • 2,370
  • 1
  • 13
  • 17