开发者

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

开发者_C百科
    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*.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜