简体   繁体   中英

C++ obtaining the short number after a string in an array of bytes

Hey so following this Question

I've gotten stuck again, and yeah I've tried looking through the web and through my textbook. I know its probably bad posting another question so soon, but I'm truly stumped on this problem. So anyways...

The next part of the assignment asks me to find the age of the person, this age is located on the next byte after the name. Basically if the name was "Bob" it would be

[L][u][k][e][\0][\0][1][5]

where all names with even number of characters get 2 null characters to make it even and then the next two bytes store a short integer. At the moment I have tried looking at the string length and then adding more onto the length before placing that onto the offset, but it doesnt seem to work

    if (name.length() % 2 != 0) {
        offset += (name.length());
        age = *((short*)foo+offset);
        cout << age << "\n";
    } else {
        offset += (name.length());
        age = *((short*)foo+offset);
        cout << age << "\n";
    }

You are missing that C and C++ multiply pointer increments by the size of the object being pointed to. So *((short*)foo+offset) actually adds offset times sizeof(short) bytes to foo.

Or maybe you understand this but don't realise that a cast has a higher precedence than an addition, (short*)foo+offset is ((short*)foo)+offset not (short*)(foo+offset).

Anyway what you want is *(short*)((char*)foo + offset) . If foo is already a char* or some similar type, then you can omit the cast to char*.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM