Search code examples
cpointersstructmallocrealloc

Source code using a structure pointer


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

}
  • In the final output

Symbol - GOOG
Shares -100
Price - 801.19
Value - %.2f

  • How is the final pointer reference at line33 leading to the output %.2f ?
    (i do understand that the %% is used to display a %]

  • Why exactly is memory reallocated in a program?

Suppose, If i were to add a realloc() function in the code for the invest pointer, how is it going to affect the program or make it better in terms of performance?
How does realloc() helps in 'freeing' the memory?

(Iam not able to quite understand the relation of realloc() with malloc())


Solution

  • %%.2f needs an extra % symbol to make the final .2f into a format rather than the string literal that's being displayed.

    Secondly realloc is intended to resize a previously calloc-ed array in memory.