user681007
user681007

Reputation:

Cast char* to int

I am writing some code to get a hex dump of the stack in c. I keep getting a compile error on this following line when I compile it using gcc in ubuntu however it compiles fine under gcc in windows.

char buffer[10];
for (int i=0;i<20;i++)
    printf("0x%lx => 0x%lx\n", &(buffer[i]), ((long *)buffer)[i]);

This is the message the compiler gives.

warning: format ‘%lx’ expects type ‘long unsigned int’, but argument 2 has type ‘char *’

Can someone please tell me if I am doing someting wrong?

Upvotes: 1

Views: 586

Answers (2)

Robᵩ
Robᵩ

Reputation: 168626

Try:

char buffer[10];
for (int i=0;i<20;i++)
    printf("%p => 0x%lx\n", (void*)&(buffer[i]), ((long *)buffer)[i]);

The 2nd arg, &(buffer[i]) is of type char*, so it needs a cast and a %p.

The 3rd arg, ((long *)buffer)[i], is of type long, so it needs a %lx.


Aside: Please realize that if buffer is not long-aligned, you might get the right answer, the wrong answer, or a core dump, all depending upon your CPU, OS, OS settings, and/or compiler.

If it were me, I'd try:

long l;
for(int i = 0; i < 20; i++)
    printf("%p => 0x%lx\n", (void*)(&l+i), *(&l+i));

Upvotes: 2

cnicutar
cnicutar

Reputation: 182639

You should be using %p to print pointers, and remember to cast to void *.

printf("%p => ??\n", (void *)&(buffer[i]), ...);

I'm not sure what you're trying to do but if you're trying to interpret a portion of buffer as a long and print it than you can use %ld.

Upvotes: 3

Related Questions