简体   繁体   中英

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?

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 .

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM