This is my code:
#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);
}
What I'm trying to see on the screen from running this code is:
Count=3
1 Test
2 Test2
3 Test3
But instead, I see:
Count=3
1 Test3
2
3
Therefore my additem function isn't working correctly. I find that a fix is to add myitems++;
right after each function call, but I'm trying to make the same behavior happen inside the additem function so that I won't have to use myitems++;
outside of the function. What else can I do to solve this?