I have an issue that's really confusing me... Below I am calling an initialize function:

void Initialize (List *L) {
    char* initialize = "initialize";
    int i;
    
    for (i=0; i<MAXLISTSIZE; i++) {
        strncpy(L->items[i].name,initialize,MAXNAMESIZE);
        L->items[i].name[MAXNAMESIZE - 1] = '\0';
        L->items[i].grade = 0;
    }
    
    L->count = 0;

}

And it seems to work, I print the values in the loop and it's fine. If I also print inside an identical loop in main to double check it works as well but If I just print the values in main after the initialize function (no print statements in Initialize) I get complete garbage.

It seems the memory I'm storing my values in isn't staying consistent and I can't figure out why.

Do I need to malloc memory for the structs? Since I don't need a variable amount of storage I thought it was not necessary... I am unsure of how to go about that.

My Structs:

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


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

Thank you for your time!

How and what are you calling Initialize (List *L) with.

Note: You have this

L->items[i].name[MAXNAMESIZE - 1] = '\0';

Shouldn't it be

L->items[i].name[strlen(initialize)] = '\0';

...After checking the docs I found strncpy pads the destination with '\0' so my point is null void.

Edited 5 Years Ago by gerard4143: n/a

I am calling it from my main here:

int main () {
    List *newList;
    int position = 2;
    Item X;
    int i;
    
    strcpy(X.name, "bob");
    X.grade = 87;
    
    /*call initialize function*/
    newList = callInitialize();
    for (i=0; i<MAXLISTSIZE; i++) {
       printf("L->items[%d].name = %s\n", i, newList->items[i].name);
       printf("L->items[%d].grade = %d\n", i, newList->items[i].grade);
       }

return 0;

}

I have

extern void Initialize (List *L);

in a header file.

And I think

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

should work ok since my MAXNAMESIZE defines the length of name anyway. I tried it with strlen and got the same junk in my values.

Edited 5 Years Ago by cdn88: wrong code

I am really sorry! This is my call to Initialize.

List *callInitialize () {

    List *L;

    List studentList;
    L = &studentList;

    Initialize(L);

return L;
}

Edited 5 Years Ago by cdn88: cleaning

I am really sorry! This is my call to Initialize.

List *callInitialize () {

    List *L;

    List studentList;
    L = &studentList;

    Initialize(L);

return L;
}

Your function callInitialize is returning a pointer to a local variable studentList? When callInitialize returns that variable will be invalid memory.

Edited 5 Years Ago by gerard4143: n/a

This question has already been answered. Start a new discussion instead.