Saturday, April 19, 2025

C++ Struct and Pointers

Other way to extract values from our Book_1 "row" based on Book "database" is to use a pointer.

The situation is similar to a previous tutorial, except we use "->" while extracting data from "columns".

This is our function that will accept a pointer to Book_1 as parameter:

void getStuff(struct Books *genField) {

    cout << "Book_1 - Title:  \t" << genField->Title   << endl;
    cout << "Book_1 - Author: \t" << genField->Author  << endl;
    cout << "Book_1 - Topic:  \t" << genField->Topic   << endl;
    cout << "Book_1 - ID:     \t" << genField->id_book << endl;

    cout << "-------------------------------------" << endl;

}

So, this is full source of our program: 

#include <iostream>
#include <cstring>

using namespace std;

void getStuff(struct Books *genField);

struct Books {
    char Title[50];
    char Author[50];
    char Topic[100];
    int id_book;
};

int main() {

    struct Books Book_1;

    strcpy(Book_1.Title, "Relativity T");
    strcpy(Book_1.Author, "Albert E");
    strcpy(Book_1.Topic, "Relativity");
    Book_1.id_book = 4323;

    getStuff(&Book_1);

    return 0;

}

void getStuff(struct Books *genField) {

    cout << "Book_1 - Title:  \t" << genField->Title   << endl;
    cout << "Book_1 - Author: \t" << genField->Author  << endl;
    cout << "Book_1 - Topic:  \t" << genField->Topic   << endl;
    cout << "Book_1 - ID:     \t" << genField->id_book << endl;

    cout << "-------------------------------------" << endl;

}

Result:

Book_1 - Title:         Relativity T
Book_1 - Author:        Albert E
Book_1 - Topic:         Relativity
Book_1 - ID:            4323
-------------------------------------

Process returned 0 (0x0)   execution time : 0.059 s
Press any key to continue.

Well done, actually - excellent.

C++ is not easy language to learn. Give yourself some time if you don't understand everything from these tutorials at first reading.

Once where you grasp basic of C++, all other languages will look easy. Take your time.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...