The Gateway to Computer Science Excellence
0 votes
55 views
#include<stdio.h>
int main() {
     int *p; 
     p = (int *)malloc(20); 
     printf("%d\n", sizeof(p)); 
     free(p); 
     return 0; 
}

malloc(20) reserves 20 bytes, why output is 8?

in Programming by Active (2.3k points)
edited by | 55 views
0
p is an integer pointer that stores addresses. In your system, the compiler uses an 8 byte pointer.

In C, you need to manually keep track of the data lenth.

Even though you try to find the sizeof(*p) you will obtain the size of the first integer(in this case) = sizeof(int).
0
Size of int and size of int pointer should not be equal?
+3
Size of every type of pointer is same because they all store addresses.  The only reason we have different type of pointer is because thats how the compiler knows how much data should be accessed at once.

There is no relation between size of int and size of int pointer. It can  be different or same depends on the platform (which includes processor, OS, compiler, compiler-options, etc).
0
Thanks a lot

1 Answer

0 votes
sizeof(int *)  is storing address of memory which is pointing to integer data but at last it is storing memory address so it depends on your machine 64 bit or 32 bit machine

sizeof(int ) is size of integer your compiler is supporting
by Active (3.7k points)

Related questions

0 votes
1 answer
3
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,257 answers
198,086 comments
104,734 users