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.

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.

I see where your calling callInitialize() but not where your calling Initialize().

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

List *callInitialize () {

    List *L;

    List studentList;
    L = &studentList;

    Initialize(L);

return L;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.