struct函数测试

    xiaoxiao2024-12-08  64

    #include <stdio.h> #include <stdlib.h> typedef struct { int a[2]; double d; } struct_t; double fun(int i) { volatile struct_t s; s.d = 3.14; s.a[i] = 1073741824; /* Possibly out of bounds */ return s.d; /* Should be 3.14 */ } int main(int argc, char *argv[]) { int i = 0; if (argc >= 2) i = atoi(argv[1]); double d = fun(i); printf("fun(%d) --> %.10f\n", i, d); return 0; } typedef struct { int a[2]; double d; } struct_t;

     typedef struct tagMyStruct    {      int iNum;     long lLength;    } MyStruct;

        上面的tagMyStruct是标识符,MyStruct是变量类型(相当于(int,char等))。

    volatile struct_t s;

    volatile是一个类型修饰符(type specifier).volatile的作用是作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值。volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。

    运行结果如下:

    /* gec@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out 0 fun(0) --> 3.1400000000 gec@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out 1 fun(1) --> 3.1400000000 gec@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out 2 fun(2) --> 3.1399998665 gec@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out 3 fun(3) --> 2.0000006104 gec@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out 4 fun(4) --> 3.1400000000 段错误 (核心已转储)

    */

    由结果可知,结果并不都是唯一的,这是因为数据多次入栈,数组会溢出,导致结果错误。

    最新回复(0)