Sandeep Singh
Sandeep Singh

Reputation: 5181

Typecasting Unsigned Long Long to Character Pointer in C

I have legacy code which contains the following code logic:

unsigned long long address; /* Its content = Some Address, not a normal value */

strcmp (address, (const char*)some_char_buffer);

This gives a warning with gcc.

Can somebody suggest some way of typecasting the variable 'address' into a char pointer so that it can be decoded properly and gcc gives no warning?

Upvotes: 1

Views: 4518

Answers (3)

Timothy Jones
Timothy Jones

Reputation: 22125

Assuming the content of address is really just a pointer: You can probably do:

strcmp ((char*)address, (const char*)some_char_buffer);

But if that's the case, it would be much better to instead change address to be a char* everywhere:

char* address; 

Depending on your codebase that may be a larger change. Do you know why it was an unsigned long long rather than a pointer in the first place?


Alternatively, if you want the bytes of the content of address to be treated as a string: (rather than the content that address might point to), do:

strcmp ((char*)&address, (const char*)some_char_buffer); // note the &

Note that you'd need the last byte in the long to be '\0' in this case. If this is what you want to do, I'd recommend using strncmp() limited to the size of the long long instead:

strncmp((char*)&address, (const char*)some_char_buffer, 
        sizeof(unsigned long long));

Upvotes: 2

jørgensen
jørgensen

Reputation: 10551

Your code should probably be using uintptr_t for address. (I do not think the standard gives a guarantee that unsigned long long has enough bits to hold a pointer, even if it does often in practice.)

uintptr_t address = ...;
strcmp((const char *)address, some_char_buffer);

either that or, if you can live with the ugliness,

unsigned long long address = ...;
strcmp((const char *)(uintptr_t)address, some_char_buffer);

Upvotes: 2

ciphor
ciphor

Reputation: 8288

Try this:

strcmp((char*)&address, (const char*)some_char_buffer);

Upvotes: -2

Related Questions