【发布时间】:2015-03-10 07:35:44
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
struct stock {
char symbol[5];
int quantity;
float price;
};
struct stock *invest;
/*Create structure in memory */
invest=(struct stock *)malloc(sizeof(struct stock));
if(invest==NULL)
{
puts("Some kind of malloc() error");
exit(1);
}
/*Assign structure data */
strcpy(invest->symbol,"GOOG");
invest->quantity=100;
invest->price=801.19;
/*Display database */
puts("Investment portfolio");
printf("Symbol\tShares\tPrice\tValue\n");
printf("%-6s\t%5d\t%.2f\t%%.2f\n",\
invest->symbol,
invest->quantity,
invest->price,
invest->quantity*invest->price); /* I dont understand this line */
return(0);
}
- 在最终输出中
符号 - GOOG
分享 -100
价格 - 801.19
值 - %.2f
line33处的最终指针引用如何导致输出 %.2f ?
(我确实理解 %% 用于显示 %]为什么要在程序中重新分配内存?
假设,如果我在代码中为 invest 指针添加一个realloc() 函数,它将如何影响程序或使其在性能方面更好?realloc() 如何帮助“释放”内存?
(我不太明白realloc()与malloc()的关系)
【问题讨论】:
-
我明白 %% 用于显示 %。这就是
%%.2f输出%.2f的原因。 -
另请注意:您似乎在编译时没有警告。
invest->price=801.19应该发出缩小警告。801.19是一个double文字,它被填充到float值中(尝试801.19f)。 -
我使用
code::blocks,我可能需要在其中更改编译器的设置。它有时不会对旨在为初学者显示警告的代码显示警告。帮助不大? -
关于casting the result of malloc的必填链接。现在我真正想知道的是,那些一直教初学者这样做的白痴是谁?
标签: c pointers struct malloc realloc