I have some code that takes an int and store it in a struct. When I read in the value the int becomes another int that is negative. I write in 2 int console but the int gets the value -842150451.
Stock.c
struct tShirt* addStock() {
int amount;
struct tShirt *location;
int i;
printf("Amount of T-shirts to register: ");
scanf_s("%d", &amount);
location = (struct tShirt *) malloc(amount * sizeof(struct tShirt));
for (i = 0; i < amount; i++) {
printf("~~~~~~~~~~~~~~~~~~~~\n");
printf("Color on shirt: ");
scanf_s("%s", location[i].color, 10);
printf("Shirt size: ");
fflush(stdin);
scanf_s("%d", location[i].size); //Problem!
printf("Color: %s and size: %d", location[i].color, location[i].size);
}
return location;
}
Stock.h Here the struct is defined.
struct tShirt* addStock();
struct tShirt {
int size;
char color[10];
};
I tried to usr -> instead of dot but then the variable get red line under it.
Change the problem line to:
scanf_s("%d", &location[i].size);
scanf reads into pointers. You didn't provide a pointer in the size case. This is a common scanf source of errors.
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.