【问题标题】:structure variable doesnot get initialized in c结构变量未在 c 中初始化
【发布时间】:2013-08-30 01:25:53
【问题描述】:

我正在尝试运行一个程序,该程序在 c... 中实现具有结构的函数,即:

#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);
}  

当我初始化 struct store item = {"xyz",10.895,10} ; 时,成员没有存储值,即 ater this (struct商店项目)排队成员:

  1. item.name 应该是 "xyz"

  2. item.price应该是10.895

  3. item.quantity 应为 10

除了 item.name=xyz 其他成员采用自己的 garbage 值..我无法理解这种行为...... 我正在使用 devc++(带有 mingw 的 5.4.2 版)...

我遇到问题是因为我使用 char name[20] 作为 struct store 的成员吗???

请有人帮忙删除我的代码中的错误..尽快回复

【问题讨论】:

  • 发布你得到的输出..
  • 除了不合适的printf,考虑看看这个stackoverflow.com/questions/330793/…
  • 我不知道你可以分配这样的结构。
  • main() 应该是int main(void)
  • @Jim:那是初始化,不是赋值。

标签: c struct char initialization


【解决方案1】:

请注意,item.quantity 将给出 10。然后将 %d 更改为 %fitem.price,因为它是一个浮点类型变量。

【讨论】:

    【解决方案2】:

    您正在使用%d 格式说明符来打印float,这是未定义的行为。您应该使用 %f 来表示浮点数和 %d 来表示整数。对于您的代码,应该是:

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

    因为item.price 是一个浮点数。

    在以后的printf 中,您还使用%d 来打印字符串item.name。应该改为%s

    【讨论】:

    • 对于那些不知道的人,%ffloatdouble 的正确格式(因为float 的参数printf 被提升为double)。
    • @interjay,, 是的.. 我在 8 月 25 日才明白.. 感谢您的回复...顺便说一句,这真是一个愚蠢的错误...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2014-05-25
    相关资源
    最近更新 更多