cdn88
cdn88

Reputation: 29

Changing values of an array containing a struct printing

I would like to access the name field from the array items and print the name but I am having trouble.

I created a pointer 'L' in callInitialize and set it to the upper struct type List which I named 'studentList'.

int callInitialize () {

/*Initialize a List*/
List studentList;
List *L;
L = &studentList;
Initialize(L);

#ifdef DEBUG
    printf("L->count after function call Initialize = %d\n", L->count);
    printf("L->items[0].name after function call Initialize = %s\n", studentList.items[0].name);
#endif 

return 0;
}

I then called Initialize and tried to set the value to test but this is incorrect.

void Initialize (List *L) {
char test = "I like you";
L->count = 0;
L->items[0].name = test;
}

I am unsure of why L->items[0].name = test; is not appropriate. I am getting an incompatible types error but name is char and test is char?

Also, once I do change that value how would I print that? My thinking was that %s would be correct since the type of the field name is char. Print is above in callIntialize as a debug statement.

My struct declarations:

#define MAXNAMESIZE 20
typedef struct {
char name[MAXNAMESIZE];
int grade;   
} Student;

typedef Student Item;
#define MAXLISTSIZE 4
typedef struct {
Item items[MAXLISTSIZE];
int count;
} List;

Thank you for any help.

Upvotes: 1

Views: 712

Answers (1)

Dmitri
Dmitri

Reputation: 9385

String copying in C doesn't work like that. Strings are simply arrays of characters, with a null character as the last element used; so to copy a string you need to copy the individual characters from the source array to the corresponding elements in the destination array. There are library functions for doing this, such as strncpy().

So you would need to change:

L->items[0].name = test;

..to something like:

strncpy(L->items[0].name,test,MAXNAMESIZE);
L->items[0].name[MAXNAMESIZE - 1] = '\0';

..where the second line just makes sure there's a null character at the end, in case test was longer than MAXNAMESIZE.

If the name member of Student had been declared as a char * and allocated with malloc(), rather than declared as an array of char, the assignment would have worked, but probably not done what you wanted -- it would have changed name to point to the same string as test (not a copy of it) and just discarded the original value, leaking the malloc()ed memory.

Upvotes: 3

Related Questions