1.C语言内存没有属性,本质就是一段01区域, 没有所谓的类型int, char, float 等等,仅仅表示一段内存空间。上代码。
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct tag{ 5 int a; 6 int b; 7 }NODE; 8 int main(int argc, const char *argv[]) 9 { 10 int *p = (int *)malloc(2 * sizeof(int)); 11 p[0] = 1; 12 p[1] = 2; 13 NODE * arr = (NODE *)p; 14 printf("%d ", arr->a); 15 printf("%d ", arr->b); 16 return 0; 17 }
p指向8个字节的内存空间,并对该段内存赋值, 伺候将该段类型强制转换为结构体类型, 结果还是一样,这说明内存没有类型属性。就是一段01空间。
2.再写一个比较有代表性的例子。注意本地计算机一般都是小端模式。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <strings.h> 4 5 int main(int argc, char* argv[]){ 6 char * p = (char *)malloc(4 * sizeof(char)); 7 /* 8 p[0] = ' '; 9 p[1] = ' '; 10 p[2] = ' '; 11 p[3] = '1';*/ 12 p = "1 "; 13 int *q = (int*) p; 14 printf("*q : %x ", *q); 15 return 0; 16 }