Fill three book structures with info using a pointer array - C Structure

C examples for Structure:Structure Definition

Description

Fill three book structures with info using a pointer array

Demo Code

#include <stdio.h>
#include <stdlib.h>

struct bookInfo {
    char title[40];
    char author[25];
    float price;/*  www.  jav a  2 s . c o m*/
    int pages;
};

int main(){
    struct bookInfo * books[3]; // Array of three structure variables

    for (int i = 0; i < 3; i++){
        books[i] = (struct bookInfo*)malloc(sizeof (struct bookInfo));
        printf("What is the name of the book #%d?\n", (i+1));
        gets_s(books[i]->title);
        puts("Who is the author? ");
        gets_s(books[i]->author);
        puts("How much did the book cost? ");
        scanf(" $%f", &books[i]->price);
        puts("How many pages in the book? ");
        scanf(" %d", &books[i]->pages);
        getchar(); //read newline input 
    }

    for (int i = 0; i < 3; i++){
        printf("#%d: %s by %s", (i+1), books[i]->title, books[i]->author);
        printf("\nIt is %d pages and costs $%.2f", books[i]->pages, books[i]->price);
        printf("\n\n");
    }

    return(0);
}

Result


Related Tutorials