2

i am trying to run a program implementing a function with structures in c... which is:

#include<stdio.h>
#include<conio.h>
struct store
    {
    char name[20];
        float price;    
        int quantity;
    };

struct store update (struct store product, float p, int q);

float mul(struct store stock_value);


    main()
{
    int inc_q;
    float inc_p,value;

    struct store item = {"xyz", 10.895 ,10};  //## this is where the problem lies ##


    printf("name    = %s\n price = %d\n quantity = %d\n\n",item.name,item.price,item.quantity);

    printf("enter increment in price(1st) and quantity(2nd) : ");
    scanf("%f %d",&inc_p,&inc_q);

item = update(item,inc_p,inc_q);

    printf("updated values are\n\n");
    printf(" name       = %d\n price      = %d\n quantity    = %d",item.name,item.price,item.quantity);

    value = mul(item);

    printf("\n\n value = %d",value);
}
struct store update(struct store product, float p, int q)
{
    product.price+=p;
    product.quantity+=q;
    return(product);
}    
float mul(struct store stock_value)
{
    return(stock_value.price*stock_value.quantity);
}  

When i am initializing that struct store item = {"xyz",10.895,10} ; the values are not being stored by the members i.e. ater this (struct store item) line the members:

  1. item.name should be "xyz",

  2. item.price should be 10.895,

  3. item.quantity should be 10;

but except the item.name=xyz other members take a garbage value of their own.. i am not able to understand about this behaviour... i am using devc++ (version 5.4.2 with mingw)...

am i getting the problem because i am using char name[20] as a member of struct store???

some one please help to remove the error in my code.. reply soon

r_goyal
  • 1,117
  • 1
  • 11
  • 20

2 Answers2

10

You are using the %d format specifier to print a float, which is undefined behavior. You should use %f for floats and %d for integers. For your code, that should be:

printf("name    = %s\n price = %f\n quantity = %d\n\n", 
       item.name, item.price, item.quantity);

because item.price is a float.

In a later printf you are also using %d to print the string item.name. It should be changed to %s instead.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • For those who didn't know, `%f` is the correct format for both `float` and `double` (because `float` arguments to `printf` are promoted to `double`). – Keith Thompson Aug 27 '13 at 15:14
  • @interjay,, yup.. i did understand it just on 25th august.. thanks for replying... it was really A silly mistake by the way... – r_goyal Sep 04 '13 at 09:10
1

Please note that item.quantity will be giving 10. Then change %d to %f for item.price as it is a floating point type variable.

r_goyal
  • 1,117
  • 1
  • 11
  • 20