Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory Address Incrementation

Is there a way for me to take a memory address and advance it a certain amount that is stored in a variable? And what would that variable type have to be?

For example, in the following code I'd like to first look at data + 0, and then for each step after that look at data + sent. If I'm looking at this correctly, sent is stored as bytes, and data is a memory address.

bool sendAll(int socket, const void *data, ssize_t size) {
    ssize_t sent = 0;
    ssize_t just_sent;
    while (sent < size) {
        just_sent = send(socket, data + sent, size - sent, 0);
        if (just_sent < 0) {
            return false;
        }
        sent += just_sent;
    }
    return true;
}
like image 718
Rick_Sch Avatar asked May 12 '26 09:05

Rick_Sch


1 Answers

That's what char* will do. Pointer math, when the pointer has type T*, always works on increments of sizeof (T). And sizeof (char) == 1 by definition.

So try:

just_sent = send(socket, sent + (const char*)data, size - sent, 0);
like image 61
Ben Voigt Avatar answered May 13 '26 23:05

Ben Voigt



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!