使用C 创建列表和结构数组

我目前正在开始使用C,所以我想我会尝试创建自己的自定义列表。 这是代码:

#include  struct list { char data[10]; struct list *n; }; void clist(struct list *a) { int j=(sizeof(a)/sizeof(a[0])); j--; for(int i=0; i<j-1; i++) { struct list *next=&a[i+1]; a[i].n=next; } } int main() { struct list first = {.data="one", .n=NULL}; struct list second = {.data="two", .n=NULL}; struct list third = {.data="three", .n=NULL}; struct list arr[] = {first, second, third}; struct list *p=&arr[0]; clist(p); struct list looper = first; while(looper.n!=NULL) { printf("%s ", looper.data); looper = *looper.n; } return 0; } 

所以基本上我有一个保存char数组和指针的结构。 我初始化它们然后我尝试通过将它们放在clist方法中将它们链接在一起。 存在的问题是:似乎clist没有得到任何有用的东西,因为变量j保持为0.如果我在将数组赋予clist方法之前进行整个大小计算,那么我得到正确的3。 这是为什么?

在C中,数组参数被视为指针。 因此表达式sizeof(a)/sizeof(a[0])变为sizeof(int *)/sizeof(int)

所以你基本上得到的是(how big your address is) / (size of integer)

对此的解决方案是将数组a的元素数作为另一个参数发送给函数。

您的代码有几个错误。

第一个是内部函数clist表达式

 sizeof(a)/sizeof(a[0]) 

相当于

 sizeof( struct list * ) / sizeof( struct list ) 

并且将等于0,因为使用了整数值并且指针的大小小于指向的结构对象的大小。

您需要expicitly将数组的大小传递给函数。 但即使是变量j也确实等于数组的大小,这个代码在函数体中是无效的

 j--; for(int i=0; i 

我们假设该数组有两个元素。 在这种情况下, j初始值也将等于2.语句后

 j--; 

它将等于1并在循环内

 for(int i=0; i 

条件

 i 

将被评估为假。 因此循环将不会执行,并且不会构建列表。

这个循环也是主要的

 while(looper.n!=NULL) { printf("%s ", looper.data); looper = *looper.n; } 

将不显示最后一个元素的数据成员,因为最后一个元素的数据成员n等于NULL。

我建议您对程序进行以下修改

 #include  struct list { char data[10]; struct list *next; }; void clist( struct list *a, size_t n ) { for( size_t i = 0, j = 1; j < n; ++i, j++ ) { ( a + i )->next = a + j; } } int main( void ) { struct list first = { .data="one", .next = NULL }; struct list second = { .data="two", .next = NULL }; struct list third = { .data="three", .next = NULL }; struct list arr[] = { first, second, third }; clist( arr, sizeof( arr ) / sizeof( *arr ) ); for ( struct list *first = arr; first != NULL; first = first->next ) { printf( "%s ", first->data); } return 0; } 

它的输出是预期的

 one two three