What is the difference between %lx and %ld when printing an address from pointer?

I have tried googling the first one for %lx, but I have no good results, BUT I have successfully searched up %ld which is just long int. Necessary for printing addresses I guess, but what is %lx for?

This is where I am confused:

int main() { int value = 25; int *pointer = &value; printf("%ld\n", pointer); // prints out the address of variable value( I hope) printf("0x%lx\n", pointer); // Completely confused here, is this perhaps address in hex? } 

Would be awesome if someone can clear this confusion I am having!

I have ran this code, and I have the results, but I am still not sure what the lx does..I have seriously tried googling this "%lx" in google, but no results explaining it.

Edit: if I use 'p' to print address then have I been wrong in thinking %ld prints address? Confused.

1

2 Answers

They're both undefined behavior.

To print a pointer with printf, you should cast the pointer to void * and use "%p".

That being said:

We can talk about the difference between "%ld" and "%lx" when trying to print integers. %ld expects a variable of type long int, and %lx expects a variable of type long unsigned int.

More or less though, The difference between x, o, d and u are about how numbers are going to be printed.

  • x prints an unsigned number in hexadecimal.
  • o prints an unsigned number in octal.
  • u prints an unsigned number in decimal.
  • d prints a signed number in decimal.
  • i prints a signed number in decimal.

We can then attach l to the format string for formats like %lx to specify that instead of an int, we're using a long int (That is, an unsigned long int, or long int).

There is a table at cppreference that has additional information:

10

%p and %lx prints the address in hexadecimal while %ld prints it in decimal

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like