Take the 2-minute tour ×

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;

#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);

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;
typedef struct {
Item items[MAXLISTSIZE];
int count;
} List;

Thank you for any help.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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:

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.

share|improve this answer
@AdamRosenfield That's why the answer explicitly null terminates it after strncpy –  Dmitri Oct 1 '11 at 2:12
add comment

Your Answer


