简体   繁体   中英

Trying to figure out why my struct pointer is storing data inaccurately

I am trying to improve my C skills so I apologize if my question is long. I am having a hard time understanding as to why my struct pointer holds the wrong value in my program, I tried to debug it but I am still relatively new to C and was hoping one of you could tell me what I'm doing wrong here and how I could improve my code and what to focus on.

I am making a program that stores user data on this struct and then prints it out.

typedef struct table {
    char *firstName;
    char *lastName;
    int id;
}USER;

This function below stores the first name

void firstName(int *counter, int *check, USER *pt) {
    for (int i = *counter; i < *check; i++) {
        pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt));
        printf("Enter First Name: ");
        getchar();
        fgets(pt[i].firstName, MAX_LENGTH, stdin);
    }
}

This is just my bool function returning true or false

bool isTrue(char *decision) {
    if(*decision == 'Y') {
        return true;
    }
    else {
        return false;
    }
}

And this is my main

int main(int argc, char **argv) {
    USER *pt = calloc(1, sizeof(pt));
    int counter = 0, check = 0;
    char decision = '\0';

    while (1) {
        printf("Would you like to enter a user?(Y/N):");
        fgets(&decision, 2, stdin);
        strtok(&decision, "\n");       //remove the newline char
        if (!isTrue(&decision)) {
            break;
        }
        if (counter != 0) {
            pt = realloc(pt, sizeof(pt) * 10); //the 10 is temporary
        }
        check = counter + 1; // make sure loop only runs once.
        firstName(&counter, &check, pt);
        ++counter;  // increment counter;
    }
    printStruct(pt, &counter);

    return 0;
}

When I run it out sometimes it works fine and returns everything and sometimes it skips a value. This is what I get. It skips the value at pointer index 1 and prints garbage instead.

Would you like to enter a user?(Y/N):N
First name at array 0 is Ermir
First name at array 1 is P#1First name at array 2 is Kevin
First name at array 3 is Blaus
First name at array 4 is Adam

Also I was wondering why is it when I realloc here If i do I get a realloc error when I enter the second name.

    if (counter != 0) {
        pt = realloc(pt, sizeof(pt) * 10); //realloc(pt, sizeof(pt) * counter + 1) wont work
    }
char decision = '\0';
...
fgets(&decision, 2, stdin);

You are only allocating 1 char but are at least reading 2 chars into it. Fix by allocating a sufficiently sized array for decision.

Unrelated but in firstName() pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt)); should be pt[i].firstName = calloc (MAX_LENGTH, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM