0

This is the code snippet from my C program

struct Person {
    int id;
    char address[150];
    char citi_id[11];
    int phone;
    int type;
} user, upd;    

int main() {
    ... ...;
    ... ...;
    printf("Enter id: ");
    scanf("%d", &upd.id);

    while(fscanf(fptr, "%d;%[^;];%[^;];%d;%d ;\n", &user.id, user.address, user.citi_id, &user.phone, &user.type) != EOF) {
        if(upd.id == user.id) {
            printf("Enter your new address: ");
            scanf(" %150[^\n]", upd.address);
            // user.citi_id is correct here
            strcpy(user.address, upd.address);
            // user.citi_id changed after the strcpy function
            fprintf(fptr, "%d;%s;%s;%d;%d ;\n", user.id, user.address, user.citi_id, user.phone, user.type);
        }
    }
    fclose(fptr);
    return 0;
}

I have checked all the struct members were correct except the user.citi_id.

The value of user.citi_id updated itself by appending the user.address to its end.

The value of user.citi_id was: A1234567890

After strcpy(user.address, upd.address); /** address = "123 ABC Road" **/

the value of user.citi_id became: A1234567890123 ABC Road

Can anyone tell me if was the fscanf function still running in the while loop caused the issue, or something else?

J_dash
  • 1
  • 2
  • 2
    `citi_id` does not have enough room to store the string `A1234567890` - 11 characters require 12 bytes. – Gereon Mar 21 '22 at 08:06
  • You should add a length limit to your `scanf` format string: `"%d;%149[^;];%10[^;];%d;%d ;\n"` – Gerhardh Mar 21 '22 at 10:19
  • Thank you so much! I've got the answer now. But does anyone know why would the other struct member appended to this struct member when the size is not set – J_dash Mar 22 '22 at 03:03

0 Answers0