I tried to test the length of int
and short
type in my computer (X86_64), so I wrote two pieces of codes as bellow:
short:
short a;
scanf("%hd%hd",&a,&a+1);
printf("%hd",a+*(&a+1));
int:
int a;
scanf("%d%d",&a,&a+1);
printf("%d",a+*(&a+1));
Both work and output the right answer, but when I change to number 1
to 4
, the first one works well while the second one show a Segmentation fault
after input.
Some materials say that the lengths of short and int are all 16 bits in x86, I don't know the difference in x86_64, are they the same?
In addition, what caused the Segmentation fault
?
PS:I use gcc -Wall -O2 -o filename -lm
to compile.
I have known what's wrong with my code after reading your comments and answers.
I guessed the address of a variable is like that in assembly language, so if I get an address and add it with the length of a variable I can get the address of the following viable. I use &a+4
first to test if the length of int
is 4 BYTES
, but there was a Segmentation fault
while running, I changed 4
to 1
and get the correct value, I didn't understand why this worked? Now, I got it.
In the following code:
short a,b;
a = b = 1024;
cout << &a << endl << &b << endl;
cout << &a << endl << (&a) + 1;
An output of it is:
0xbfad153c
0xbfad153e
0xbfad153c
0xbfad153e
And
int a,b;
a = b = 1024;
cout << &a << endl << &b << endl;
cout << &a << endl << (&a) + 1;
return 0;
An Output is:
0xbfddb968
0xbfddb96c
0xbfddb968
0xbfddb96c
It shows that &a + 1
here plus the value of the size of int a
but not the literal const value
of 1
So I just want to use the feature of memory allocating to measure the size of int
and short
, not sizeof
function.
Thanks for your answers and comments, even though they are not what I want to get.