#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?
(我知道%%用于显示%]
为什么要在程序中重新分配内存?


假设,如果我要在投资指针的代码中添加realloc()函数,它将如何影响程序或使其性能更好?
realloc()如何帮助“释放”内存?

(我无法完全理解realloc()malloc()的关系)

最佳答案

%%。2f需要一个额外的%符号,以将最终的.2f转换为一种格式,而不是所显示的字符串文字。

其次,realloc旨在调整内存中先前已调用的数组的大小。

关于c - 使用结构指针的源代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28958283/

10-11 23:15