//定义一个字符型数组,用关键字sizeof求长度
#include <iostream>
int main()
{
char a[1000];
int i;
printf("hello world\n");
for (i = 0; i < 1000; i++)
{
a[i] = -1 - i;
//printf("%d\n",a[i]);
}
printf("the size of i %d\n",sizeof(i));
printf("the size of i %d\n", sizeof(char));
printf("the size of i %d\n", sizeof(a));
printf("%d\n", strlen(a));
return 0;
}
//结果
C:\Users\kanxue\Desktop\VS\ConsoleApplication1\Debug>ConsoleApplication1.exe
hello world
the size of i 4
the size of i 1
the size of i 1000
255
//定义一个singned int变量和unsigned int相加得到结果
#include <iostream>
int main()
{
int i = -20;
unsigned int j = 10;
printf("the i+j valude is %d\n", i + j);
return 0;
}
//结果很快就能得出结果,我们这里主要是分析原因
C:\Users\kanxue\Desktop\VS\ConsoleApplication1\Debug>ConsoleApplication1.exe
the i+j valude is -10
分析:编译器缺省默认情况下数据为signed类型,在计算机系统中,数值一律用补码来表示,正数的补码和原码一致,负数的补码:符号为为1,其余位位该数绝对值的源码按位取反,然后整个数加1;
-20用正常二进制表示为: 1001 0100 ,其补码为:1110 1100
10二进制表示为:0000 1010
两者相加:1110 1100 + 0000 1010 = 1111 0110 其补码为:1000 1010 -> -10
#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5};
int *ptr = (int *)( &a + 1);
printf("%d, %d, \n", *(a+1), *(ptr-1) );
return 0;
}
//结果
C:\Users\curtis\Desktop\VS\static\Debug>static.exe
2, 5,
数组名 a 的特殊之处:
&a : 代指 数组的整体 的地址,这里的 a是数组整体
a+1: 代指 数组的第一个成员,这里的 a是数组首地址
#include <iostream>
#define SQR(x) printf("The square of "#x" is %d.\n", ((x)*(x)));
int main()
{
signed i;
int *p;
printf("sizeof *p is %d\n", sizeof(p));
SQR(3);
for (i = 9; i >= 0; i--)
{
printf("%u\n", i);
}
return 0;
}
//
C:\Users\kanxue\Desktop\VS\ConsoleApplication1\Debug>ConsoleApplication1.exe
sizeof *p is 4
The square of 3 is 9.
9
8
7
6
5
4
3
2
1
0
版权声明:本文为qq_42931917原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。