Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of pointer of integer type vs Size of int*

Tags:

c

pointers

I started reading Pointers and while tinkering with them. I stumbled upon this :

#include<stdio.h>
int main()
{
    int *p,a;
    a=sizeof(*p);
    printf("%d",a);
}

It outputs : 4

Then in the place of sizeof(*p) I replaced it with sizeof(int*) Now it outputs 8 .

P is a pointer of integer type and int* is also the same thing ( Is my assumption correct? ). Then why it is printing two different values. I am doing this on a 64bit gcc compiler.

like image 819
Surya Teja Vemparala Avatar asked May 25 '15 10:05

Surya Teja Vemparala


People also ask

What is the size of a pointer to an integer?

Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes. So for a specific architecture pointer size will be fixed. It is common to all data types like int *, float * etc.

Is size of int and int * Same?

int means a variable whose datatype is integer. sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.

Is pointer the same size as int?

No, it is not correct. The size of an int and the size of a pointer vary across platforms, and they are not necessarily the same. Indeed, on modern 64-bit consumer hardware, you're likely to find 32-bit int s and 64-bit pointers.


2 Answers

Every beginner always gets confused with pointer declaration versus de-referencing the pointer, because the syntax looks the same.

  • int *p; means "declare a pointer to int". You can also write it as int* p; (identical meaning, personal preference).
  • *p, when used anywhere else but in the declaration, means "take the contents of what p points at".

Thus sizeof(*p) means "give me the size of the contents that p points at", but sizeof(int*) means "give me the size of the pointer type itself". On your machine, int is apparently 4 bytes but pointers are 8 bytes (typical 64 bit machine).

like image 102
Lundin Avatar answered Nov 15 '22 09:11

Lundin


*p and int* are not the same things! First one is a dereferenced pointer (i.e. int which is 4 bytes wide) and the second one is a pointer (8 bytes wide in your case since it's a 64 bit machine).

like image 23
banach-space Avatar answered Nov 15 '22 07:11

banach-space