Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing struct to a function

Tags:

c++

c

struct

binary


This works:

struct client {
    string address;
    int toPay;
    int id;
};

int main() {
    struct client clients[10];
    ...
    file.read( (char*)&clients, sizeof (clients) );
}

What I want to do, is do those things inside of a function.

But how would I have to pass the struct to the function?

If I pass it likes this, read doesn't work:

void newFunction ( struct client *clients_t) {
    ...
    file.read( (char*)&clients_t, sizeof (clients_t) );
}
like image 546
Simon G. Avatar asked Jun 25 '26 02:06

Simon G.


1 Answers

This is not going to work, because the string data is not embedded into the struct. Instead, it has a couple of pointers to the string content. That is why file.read( (char*)&clients...) is not going to produce a valid result: the string will point to the place where a saved string once pointed, but it would no longer represent the data of interest.

If you would like to serialize the data like that, embed an entire char array in the struct, with the obvious limitation that there would be a cap on the number of characters and some wasted space.

like image 172
Sergey Kalinichenko Avatar answered Jun 26 '26 17:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!