-4
char a[] = {'A'};
printf(This is random value %c", &a[0] );
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
SK Singh
  • 1
  • 1
  • Please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). LAstly please learn how to [edit] your questions, and how to create a [mre] to show us (which doesn't contain unrelated errors or problems). – Some programmer dude Sep 16 '21 at 06:08
  • As for your problem, it would be the same without an array, as in `char a = 'A';` and `&a`. The use of an array is a red herring. – Some programmer dude Sep 16 '21 at 06:09
  • 2
    What value did you expect when you print it? Why? – Gerhardh Sep 16 '21 at 06:19
  • `printf("The character %c lives at %p.\n", a[0], (void*)&a[0]);` – pmg Sep 16 '21 at 07:09

2 Answers2

1

This program invokes undefined behavior, as %c is not the correct conversion specifier for an address. Use %p, and cast the argument to (void*).

Note: In case the argument is of type char*, casting is optional, but for any other type, the casting is necessary.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You are printing the address incorrectly.

%c is for printing characters. To print an address use %p and cast the pointer argument (i.e. the address) to void-pointer. Like

printf(This is random value %p", (void*)&a[0] );

The C standard does not define what is supposed to happen for your program. So in principal anything may happen and random values could be the result. No one can tell for sure what your code wil do (without having expert level knowledge of the specific system you are using).

However, on most systems your code will take 1 byte from the pointer and print it as-if it was a character. So the (likely) reason for your "random characters" is that the address of the array is different every time you start the program. And that is exactly what many systems do...

They use "Address Space Layout Randomization". This basically means that the address of things in your program (here the array) are randomly determined during program start up. The idea is to make it harder for hackers to exploit your program.

Read more here: https://en.wikipedia.org/wiki/Address_space_layout_randomization

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63