0

I am brand new to C and I'm trying to get this to say how many bytes does an int/long/short have. Keep in mind I have to have the variables there so I cannot just say sizeof(int). Any help would be appreciated thanks!

#include <stdio.h>

int main()
{
short* A;
int* B;
long* C;

printf("Size of integer variable = %d bytes\n", sizeof(A));
printf("Size of integer variable = %d bytes\n", sizeof(B));
printf("Size of integer variable = %d bytes\n", sizeof(C));
return 0;
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
Skeeter
  • 33
  • 10
  • 2
    `int*` is not the same as `int`. – jwodder Sep 26 '14 at 00:28
  • 1
    ah right * is a pointer right? – Skeeter Sep 26 '14 at 00:30
  • 2
    possible duplicate of [Is the sizeof(some pointer) always equal to four?](http://stackoverflow.com/questions/399003/is-the-sizeofsome-pointer-always-equal-to-four) – Retired Ninja Sep 26 '14 at 00:30
  • Thanks everyone! It worked after I took away the '*' – Skeeter Sep 26 '14 at 00:31
  • by the way, most of the time you should define local variables as `int`. In some 64 bit systems `long` and `int` are the same thing and `int`s are just as performant as `char` when they are in a cpu register (the advantage of char is that it saver memory in arrays) – hugomg Sep 26 '14 at 00:46

2 Answers2

5

Each of the variables you are calling sizeof on is actually a pointer to a variable. These pointers, in a 64-bit application, will always be 8 bytes (8 bytes x 8 bits per byte = 64 bits), regardless of what type of variable they point to. In a 32-bit application, they would return 4 bytes (4 bytes x 8 bits per byte = 32 bits). This is because a pointer is an address to a memory location, and the size of this address is not dependent upon the size of the variable to which the pointer is pointing.

You can calculate the size of the variable to which the pointers are pointing by dereferencing the pointers in the sizeof function:

printf("Size of short variable = %d bytes\n", sizeof(*A));
printf("Size of integer variable = %d bytes\n", sizeof(*B));
printf("Size of long variable = %d bytes\n", sizeof(*C));

This will output the following (may depend on compiler):

Size of short variable = 2 bytes
Size of integer variable = 4 bytes
Size of long variable = 4 bytes
hugomg
  • 68,213
  • 24
  • 160
  • 246
Brett Wolfington
  • 6,587
  • 4
  • 32
  • 51
0

You're testing the size of a short int pointer, an int pointer, and a long int pointer respectively. On many systems, all pointers will have the same size.

You're probably interested in code that looks like this. Note the lack of *s.

#include <stdio.h>

int main()
{
    short A;
    int B;
    long C;

    printf("Size of integer variable = %d bytes\n", sizeof(A));
    printf("Size of integer variable = %d bytes\n", sizeof(B));
    printf("Size of integer variable = %d bytes\n", sizeof(C));
    return 0;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173