c - 结构变量没有在c中初始化

标签 c struct char initialization

我正在尝试运行一个程序,该程序在 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 其他成员取了他们自己的垃圾值..我无法理解这种行为...... 我正在使用 devc++(带有 mingw 的 5.4.2 版)...

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

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

最佳答案

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

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

因为 item.price 是一个 float 。

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

关于c - 结构变量没有在c中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463048/

相关文章:

c++ - 将整数转换为 char* C++

C 警告 "format ' %d' 需要类型为 'int *' 的参数,但参数 2 的类型为 'int"

c - zlib 函数找不到的符号

c - 在没有段错误的结构中使用指针

c++ - 从偏移量开始复制到结构的开头

C char[] 和 *char

c++ - 为什么表达式的结果取决于表达式的放置位置?

c - makefile,编译卡在第一个文件上的源列表

c - 关于访问不同源文件中定义的结构

matlab - 对象属性的迭代定义