views:

110

answers:

3
#include <stdio.h>
typedef struct pduct {char name[20];
                        int price;
                        int stock;} PRODUCT;

void init(PRODUCT * product)
{
    printf("What is the name of the product: ");
    fgets(product->name, 20, stdin);
    printf("DEBUG: Did it get written...: %s", product->name);
    printf("What is the current stock of the item: ");
    scanf("%d", product->stock);
    printf("What is the price of the new item: ");
    scanf("%d", product->price);
}

int main()
{
    PRODUCT products[5];
    init(products);
    return 0;
}

Now, I'm at a bit of a loss, really. Upon running this, it will ask for the name of the product, print it out so I know it stored it, then ask for the stock amount, where it will crash and return -1.

I have no idea what's going wrong. I've tried swapping out fgets with scanf, just to be sure, but the same thing happens. I'm guessing my struct is set up wrong, but I don't know how. Is it the char array maybe? Also, it's always the second input, no matter how I arrange them. So why does the first work so well?

Thanks for any help!

+9  A: 

One quick bug I can see is missing & in scanf.

scanf("%d", &product->stock);
            ^
scanf("%d", &product->price);
            ^

The compiler warns you on such mistakes:

warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

Don't ignore compiler warnings.

codaddict
Thanks! That seemed to have fixed it. GCC wasn't giving me any warnings, and I thought struct->member would resolve to an pointer.
Super_ness
struct->member will resolve to whatever it is, in this case, an int, not a pointer to int.
Ed Swangren
Use `gcc -Wall -Wextra` and either make **every single** warning go away, or be absolutely sure you know why the warning isn't an issue and why you aren't rewriting the offending code to not give a warning. I'd strongly recommend that practice to a new user of C, and encourage it in production code as well.
RBerteig
+1  A: 

You need to pass the address of product->stock. That is:

scanf("%d", &product->stock);
Jim Mischel
+1  A: 

scanf takes a pointer to where you store the result. In this case, you're using the current (uninitialized) value of stock as the address of where to write the result of the scanf. You need to say scanf("%d", &product->stock), etc.

Logan Capaldo