0
#include<stdio.h>

int main()
{
        int x = 1,*t;
        float y = 1.50,*u;
        char k = 'c',*v;

        t = &x;
        u = &y;
        v = &k;

        printf("%p %p %p", t, u, v);

        t++;
        u++;
        v++;

        printf("  %p %p %p", t, u, v);

        return 0;
}

Hi i have made this code but here something unusual is happening , i am printing the addresses , when i increase the address of all then from my view increment in int would be 2 , float would be 4 and char would be 1 but i got the following :

0xbffa6ef8 0xbffa6ef0 0xbffa6eff  0xbffa6efc 0xbffa6ef4 0xbffa6f00

For float and char i think its correct but for int i don't know why it is giving so

Sudhanshu Gupta
  • 2,255
  • 3
  • 36
  • 74
  • Why do you think `int` should only be 2 bytes? You've just proven that it's 4 (which is entirely normal - `int` is 32 bits on most platforms). On the other hand, `short` may well be 2 bytes wide... – Mac Dec 19 '11 at 04:01

4 Answers4

2

You are assuming the sizeof(int) is 2 on your system/envrionment.

However, Your assumption is not correct. The standard does not require the size of int to be 2 or anything specific.

As your program shows the size of int is 4 on your system/envrionment.

Lesson to Learn:
Never rely or assume on size of an type, always use sizeof to determine the size, that is the reason the standard provides sizeof.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

The memory address increment for t is given by sizeof(int).

If sizeof(int) is different than what you expect t to be incremented by then your assumption is wrong.

holygeek
  • 15,653
  • 1
  • 40
  • 50
1

An int data type is usually 4 bytes. a short or a short int data type is 2 bytes;

Chase Walden
  • 1,252
  • 1
  • 14
  • 31
1

The actual size of integer types varies by implementation. The only guarantee is that the long long is not smaller than long, which is not smaller than int, which is not smaller than short.

or

sizeof ( short int ) <= sizeof ( int ) <= sizeof ( long int )


But you can be sure that it will be atleast 16 bits in size.


This will be helpful,detailed informations regarding the size of basic C++ types.

Community
  • 1
  • 1
COD3BOY
  • 11,964
  • 1
  • 38
  • 56