C++ Reference to local variable vs reference to parameter

I am writing my own htonl, htons, ntohl, and ntohs functions, and I'm getting behavior I don't understand. The code below works as expected:

uint16_t htons(uint16_t hostshort)
{
    uint16_t netshort = 0;
    uint8_t* p = (uint8_t*) (&netshort);

    p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
    p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);

    return netshort;
}

uint16_t ntohs(uint16_t netshort)
{
    uint16_t hostshort = 0;
    uint8_t* p = (uint8_t*) netshort;


    hostshort |= ((uint16_t)p[0]) << 8;
    hostshort |= ((uint16_t)p[1]) << 0;


    return hostshort;
}

The problem is that this code doesn't work at all:

uint16_t htons(uint16_t hostshort)
{
    uint16_t netshort = 0;
    uint8_t* p = (uint8_t*) netshort;

    p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
    p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);

    return netshort;
}

uint16_t ntohs(uint16_t netshort)
{
    uint16_t hostshort = 0;
    uint8_t* p = (uint8_t*) (&netshort);


    hostshort |= ((uint16_t)p[0]) << 8;
    hostshort |= ((uint16_t)p[1]) << 0;


    return hostshort;
}

When I remove the & from netshort in htons, it returns all zeroes, and when I add it in ntohs, it returns garbage. Can someone please explain how they're being handled differently? My understanding was that both cases should be returning a pointer to the start of the data in memory, but they're obviously being handled differently. Is there something implicit happening with the parameter?

Answers


uint16_t netshort = 0;
uint8_t* p = (uint8_t*) netshort;

This says, take the value of netshort (which is 0), and interpret that as a uint8_t* pointer. In this case, that would be null.

This means that the following lines, assigning something to that pointer are undefined.

p[0] = (uint8_t)((hostshort & 0xFF00) >> 8);
p[1] = (uint8_t)((hostshort & 0x00FF) >> 0);

You need to take the address of the local.

uint8_t* p = (uint8_t*) &netshort;

Need Your Help

Accessing the text value of custom column with NetSuite SuiteScript

javascript netsuite

I am working with NetSuite's server-side SuiteScript and need to access the display value of several custom Transaction Column Fields. The fields in question are each set up as type "List/Record" a...

Copy to Clipboard in Chrome Extension

javascript clipboard google-chrome-extension

I'm making an extension for Google Chrome and I have hit a snag.