#include <stdio.h> #define SUB(x, y) x - y #define ACCESS_BEFORE(element, offset, value) *SUB(&element, offset) =value int main(void) { int i; int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; ACCESS_BEFORE(array[5], 4, 6); for (i = 0; i < 10; ++i){ printf("%d ", array[i]); } return 0; }
编译结果:
分析:
SUB(x, y) x - y
ACCESS_BEFORE(element, offset, value) *SUB(&element, offset) =value
ACCESS_BEFORE(array[5], 4, 6);->*SUB(&array[5], 4) =6 ->*&array[5] - 4 =6
*&array[5]的值为6,则减去4等于2,将6赋值给2,则肯定是错误的。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream> #include <string> using namespace std; struct { short a1; short a2; short a3; }A; struct { long a1; short a2; }B; int main(void) { char *ss1 = "0123456789"; // int ss[100] = "0123456789"; cout << sizeof(A) << endl; cout << sizeof(B) << endl; cout << sizeof(ss1) << endl; // cout << sizeof(ss) << endl; return 0; }
假设去掉代码中的凝视,则编译结果为:
由此可见 int ss[100] = "0123456789"; 这个语句是不对的,所以对其求sizeof也是不对的。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <stdio.h> char var[10]; int test(char var[]) { return sizeof(var); } int main(void) { printf("%d ", test(var)); return 0; }
var退化为数组的指针,而非数组。