Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does storing a pointer take more memory than the byte that it's pointing to?

Tags:

c

My questions are how where are the pointer values stored and do they take up more space in memory than the things they point to. For example, if I have a 64 bit pointer which i use to point to a byte of information in memory; where is the value of the pointer stored and does it take up more space than the data itself?

An example of my question written in C

char data = 10;

char* charPointer = &data;

doesn't charPointer take up more space than the data since the pointer is 64 bit and the data is 8 bit?

PS: I'm currently trying to learn the basics of C.

like image 654
John Issa Avatar asked Oct 14 '25 17:10

John Issa


2 Answers

where is the value of the pointer stored

The pointer's value is stored where you declared it to be stored; e.g. if you declared the pointer as a local variable, then it will be stored on the stack; OTOH if you allocated the pointer on the heap (or, more commonly, you included the pointer as a member-variable of an object that you allocated on the heap) then the pointer will be in the heap.

and does it take up more space than the data itself?

In this case, it does.

You can actually check for yourself how much space a value takes up:

printf("data takes up %zu bytes\n", sizeof(data));
printf("charPointer takes up %zu bytes\n", sizeof(charPointer));

If you are on a 64-bit machine, you should find that a pointer takes up 8 bytes, as you would expect.

The char that the pointer points to takes up one byte, but in many cases there will also be some padding bytes inserted to keep the alignment of the next item on the stack optimal for the CPU to access efficiently.

like image 144
Jeremy Friesner Avatar answered Oct 17 '25 08:10

Jeremy Friesner


A pointer to a char takes more space than a char in practically every C implementation. (The C standard permits them to be the same size, but such implementations are at best rare and are more likely archaic or nonexistent.)

Nonetheless:

  • One may need a pointer to point to one of a selection of objects or to manage objects or to connect them in various ways.
  • A pointer may point to objects much larger than a char.
  • A pointer may point to the first of many elements in an array, so one pointer can provide access to many objects.
like image 30
Eric Postpischil Avatar answered Oct 17 '25 09:10

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!