我也是Linux环境的牙,我代码改了,主要是去掉了那个NULL,那个是我试验断言用的~~运行代码结果如下:
程序代码:
yiran@yiran-ubuntu:~$ cat test.c #include <stdio.h> #include <assert.h> struct shm_data_st { struct shm_data_st *pre; char data[10]; struct shm_data_st *next; }; struct shm_data_st* init_shm_data(memory, size) void *memory; size_t size; { struct shm_data_st *pt = memory; struct shm_data_st *end = memory + size; assert(memory != NULL && size != 0); for (; pt < end; ++pt) { pt->pre = pt - 1; sprintf(pt->data, "struct %d", pt - (struct shm_data_st*)memory); pt->next = pt + 1; } ((struct shm_data_st*)memory)->pre = NULL; pt[-1].next = NULL; return memory; } int main(void) { char buf[1000]; struct shm_data_st *pt; init_shm_data(buf, 1000); for (pt = (struct shm_data_st*)buf; pt != NULL; pt = pt->next) puts(pt->data); return 0; } yiran@yiran-ubuntu:~$ gcc test.c -o test yiran@yiran-ubuntu:~$ ./test struct 0 struct 1 struct 2 struct 3 struct 4 struct 5 struct 6 struct 7 struct 8 struct 9 struct 10 struct 11 struct 12 struct 13 struct 14 struct 15 struct 16 struct 17 struct 18 struct 19 struct 20 struct 21 struct 22 struct 23 struct 24 struct 25 struct 26 struct 27 struct 28 struct 29 struct 30 struct 31 struct 32 struct 33 struct 34 struct 35 struct 36 struct 37 struct 38 struct 39 struct 40 struct 41 struct 42 struct 43 struct 44 struct 45 struct 46 struct 47 struct 48 struct 49 yiran@yiran-ubuntu:~$