SK Singh
SK Singh

Reputation: 1

Why address(&) give random variable with array?

char a[] = {'A'};
printf(This is random value %c", &a[0] );

Upvotes: -4

Views: 71

Answers (2)

4386427
4386427

Reputation: 44340

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

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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.

Upvotes: 1

Related Questions