0

In this program I have located char pointer. I have located 1 byte of memory in heap. But when I print its size it shows 4 bytes. please help.

//CODES//

#include <stdio.h>
#include <stdlib.h>
int main(){
char *ptr;
ptr=(char*)malloc(1);
printf("The size is %d.",sizeof(ptr));
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 5
    `sizeof(ptr)` gives the size of the pointer which is always 4 bytes on your system. It does not give the size of the buffer the pointer points to. – kaylum Nov 23 '20 at 04:24
  • 1
    There is no (portable) way at runtime to ask how large a malloc'ed buffer is, you have to remember what it was that you asked for. In particular `sizeof` certainly won't do it. – Nate Eldredge Nov 23 '20 at 04:25
  • Try `sizeof *ptr` or `sizeof ptr[0]`. Note that `sizeof` does not need nor utilizes parentheses - the parentheses are only needed for *type names* when used in `sizeof` as opposed to expressions. – Antti Haapala -- Слава Україні Nov 27 '20 at 04:11

0 Answers0