【发布时间】:2015-10-10 17:32:45
【问题描述】:
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char item[1000];
} itemset;
void additem(itemset* items,char* thing,unsigned long* numadded){
memcpy(items->item,thing,1000);
items++;(*numadded)++;
}
void showitems(itemset* items,unsigned long numitems){
itemset* p=items;
unsigned long count;
for (count=1;count<=numitems;count++){
printf("%d %s\n",count,p->item);p++;
}
}
int main(){
itemset* myitems=calloc(1,sizeof(itemset)*10);
itemset* itemstart=myitems;
unsigned long added=0;
additem(myitems,"Test",&added);
additem(myitems,"Test2",&added);
additem(myitems,"Test3",&added);
printf("Count=%d\n",added);
showitems(itemstart,added);
free(itemstart);
}
我试图通过运行此代码在屏幕上看到的是:
Count=3
1 Test
2 Test2
3 Test3
但是,我看到了:
Count=3
1 Test3
2
3
因此,我的 additem 功能无法正常工作。我发现解决方法是在每个函数调用之后立即添加 myitems++;,但我试图在 additem 函数内部发生相同的行为,这样我就不必在函数外部使用 myitems++;。我还能做些什么来解决这个问题?
【问题讨论】:
标签: c function pointers struct