1

I recently came across the question in an interview. "What is the size of a pointer in C?".

My first thought was to ask, "well it depends on the computers operating system whether we are working in 64-bit, 32-bit, 8-bit etc." From my previous knowledge working with C (mostly in python now) I remember that if we are in 32-bit OS then the size of a pointer would be 4 bytes and in 64-bit OS 8 bytes. Can someone elaborate more clearly? or correct me if I am mistaken?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tanner Dolby
  • 4,253
  • 3
  • 10
  • 21
  • 5
    Yes, it varies between architectures. Also, on some machines, data pointers and function pointers are different sizes. – Jonathan Leffler Dec 01 '19 at 23:47
  • It can very even "on" the same architecture. For example, I believe that modern versions of Linux and Windows can run both 32-bit and 64-bit executables side by side. – Steve Summit Dec 01 '19 at 23:53
  • 2
    Note that the IBM iSeries (AS/400, OS/400) machines use 16-byte pointers. For example, see the discussion in [Chapter 22: Using OS/400 pointers in a program](https://www.ibm.com/support/knowledgecenter/SSAE4W_9.5.1/com.ibm.etools.iseries.pgmgd.doc/cpprog440.htm) and also [Chapter 29: Using Teraspace in ILE C and C++ programs](https://www.ibm.com/support/knowledgecenter/SSAE4W_9.5.1/com.ibm.etools.iseries.pgmgd.doc/cpprog588.htm). There are also 8-byte pointer libraries; code compiled for 8-byte pointers can't link with 16-byte pointer libraries and vice versa. (16-byte pointers are 'native'.) – Jonathan Leffler Dec 02 '19 at 00:09
  • @JonathanLeffler The data pointers and function pointers were what I needed to investigate. Thanks! – Tanner Dolby Apr 17 '20 at 16:56

1 Answers1

0

the size of a pointer

printf("%zu bits\n", sizeof (your_pointer_type_here) * CHAR_BIT);

Your could see 16, 32, 48, 64 bit, or all sorts of other values. 16,32,64 are certainly the most popular.

C allows all sorts of architectures besides "32-bit OS" with 4-byte pointer and "64-bit OS" with 8. It is compiler dependent influenced by what is possible on a given architecture.

Size may depend on type

A function pointer need not be the same size/encoding as a object pointer.

Also a int * may differ form a double * for example, yet all object pointers convert to/from a void * - even when of different sizes.


Good code avoid needing to know the size, but adapts as needed.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256