Question

I am trying to convert a self-defined char constant (using #define in a header file) holding a Port number, to an unsigned Short int (in order to be able to handle it using htons() to get the network Byte-Order). I defined a structure in a separate header, grouping PORT, HOSTNAME, and a GAMEKINDNAME (I believe the constants name are pretty self-explanatory; they are all respectively stored as char-arrays).

The specification of the initialized structure looks like this:

    struct Config configuration_parameters = {
    .type_of_game = GAMEKINDNAME,
    .hostname = HOSTNAME,
    .port = (unsigned short) PORT
    };

While compiling, I get the following errors:

warning: cast from pointer to integer of different size
error: initializer element is not constant

I thought that this might be caused by the fact that char uses 1 Byte of storage, while unsigned short uses 2 Bytes of storage, that this might represent some sort of conflict... Is this assumption right, and if so (or even if not), anyone have an idea on how to fix this?

Any help would be appreciated!

Was it helpful?

Solution

I assume your declaration for PORT looks more or less like this:

const char *PORT = "12345";

if you cast that to unsigned short you will not cast the value, but instead the pointer to "12345". Use a function like atoi to achieve that:

struct Config configuration_parameters = {
    .type_of_game = GAMEKINDNAME,
    .hostname = HOSTNAME,
    .port = 0
    };
configuration_parameters.port = (unsigned short)atoi(PORT);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top