1

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.

Morpfh
  • 3,793
  • 14
  • 23
Olof
  • 696
  • 11
  • 29
  • 1
    I think you need to pass the address of size: scanf_s("%d", &(location[i].size)); – George Houpis Dec 10 '14 at 20:04
  • `fflush(stdin)` causes undefined behaviour. [See here](http://stackoverflow.com/a/26081123/1505939) for a better option – M.M Dec 10 '14 at 21:10

1 Answers1

2

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.

Angus Comber
  • 8,150
  • 10
  • 49
  • 92