5

Compiler says my pointer is 4 bytes, but my computer is 64 bit OS. shouldn't it say it's 8 bytes instead of 4 bytes? what's causing this problem? is the IDE doing this? perhaps, the compiler maybe?

int *p;
printf("%d", (int)sizeof(p));


compiler says: 4
Nas
  • 51
  • 1
  • 4
  • 3
    Please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) showing us how you check the size of the pointers. – Some programmer dude Oct 11 '18 at 10:40
  • 2
    What is your compiler? How do you compile? May be you compile for a 32 bits architecture on a 64bits host (the default behavior for some Visual Studio version)? – Mathieu Oct 11 '18 at 10:40
  • [Difference between C 8 bit 16-bit 32-bit compilers](https://stackoverflow.com/q/15827452/2173917) – Sourav Ghosh Oct 11 '18 at 10:41
  • 1
    `printf("(void*) needs %d bits\n", (int)(CHAR_BIT * sizeof (void*)));` – pmg Oct 11 '18 at 10:43
  • 1
    That code you show actually have [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior), since you have mismatching format specification and argument type. The `sizeof` operator results in a value of type `size_t`, and if you want to print it you should use `"%zu"`. See e.g. [this `printf` reference](https://en.cppreference.com/w/c/io/fprintf) for details. The probable reason it seems to work is the same reason you get the unexpected result: You're building for a 32-bit target. – Some programmer dude Oct 11 '18 at 10:56
  • 1
    You still need to describe what your build options were when compiling/linking your code. – lurker Oct 11 '18 at 11:07

2 Answers2

5

Your compiler and compiler options define what is the actual target. Operating system does not matter too much as you can compile 64bit code on the 32 bit machine (you will not be able to execute it), and 32 bits code on the 64 bits machine.

If sizeof of the pointer is 4 bytes it means that you compile 32 bit code. On many 64 OSes you can execute the 32bit code.

0___________
  • 60,014
  • 4
  • 34
  • 74
2

I was looking for the same answer and i found out that I have to change //Build -> Configuration Manager -> Active solution platform to x64 // to make it a 8 byte value. Hope this helps if you are using the Visual Studio Community 2019.