Reputation: 899
I am trying to retrieve values from an array of structs. I do not know the correct ways to retrieve them.
Here is my struct:
struct entry{
char name[NAME_SIZE];
int mark;
};
typedef struct entry Acct;
Acct dism2A03[MAX_ENTRY];
How i assigned values:
void add_new(char *name,int mark){
printf("%s,%d",name,mark);
int v=0;
v=entry_total;
strcpy(dism2A03[v].name,name);
dism2A03[v].mark = mark;
}
What i tried (DOES NOT WORK):
int m=0;
for(m=0;m<MAX_ENTRY;m++){
char name[NAME_SIZE] = dism2A03[m].name;
line 75 >> int mark = dism2A03[m].mark;
printf("\nEntry %d",m);
printf("%s",name);
printf("%d",mark);
}
ERROR: p9t2.c: In function ‘main’: p9t2.c:75:5: error: invalid initializer
Upvotes: 1
Views: 76
Reputation: 727047
Your first attempt implies existence of getfield
function that takes a struct
and a multicharacter char
literal and gets the field; there is no such function in C.
Your second attempt is much closer: rather than trying to assign the name to an array, assign it to a char
pointer, like this:
int m=0;
for(m=0;m<MAX_ENTRY;m++){
// Since you aren't planning on modifying name through pointer,
// you can declare the pointer const to make your intentions clear.
const char *name = dism2A03[m].name;
int mark = dism2A03[m].mark;
printf("\nEntry %d",m);
printf("%s",name);
printf("%d",mark);
}
Upvotes: 2