Click here to Skip to main content
15,667,466 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I want to find the memory address of a character but i have noticed somethings and i am unable to understand it.

char name[] = {"hello"};

// to find the memory address of name array this is what i did

cout<<"The memory address of name[] is:"<<&name[]<<endl;

//this works fine and now i want to find the memory address of a character in the
name array

// say i want to find the memory address of char h || char e
//so this is what i did for finding the address

cout<<"The memory address of name[0] is:"<< &(name[0])<<endl;
//now here is the problem, i get wrong results, what i get is "hello" instead of getting the memory address

// i looked online and found this trick to find the memory address of name[0]
cout<<"the memory address of name[0] is:"<<static_cast<void>(&(name[0])<<endl;

I dont understand why the normal approach of &(name[0]) dint work and what is the meaning of static_cast<void>(&(name[0]) and what does it do?
Please can anyone explain me in simple terms. Thanks
Updated 21-Dec-22 7:19am

1 solution

What you have is an array of chars. name[0] will return the first char, and &name[0] will return a pointer (the memory address) to that char (a char*), as you expect.
What's happening though, is that cout is interpreting that char* as a string and printing out the characters instead of the address.

The trick you found using static_cast is close, but it's missing a crucial part - the type to cast to, the aim is to cast the char* to a void* so that cout won't treat it as a string.
char name[] = "Hello";
cout<<"the memory address of name[0] is:"<<static_cast<void*>(&name[0])<<endl;

For more info on different types of casts (as static_cast is not the only one) see[^]
Share this answer
Rebecca1995 27-Sep-14 11:27am    
@anthony mushrow:- amazing explanation and hats off for clarity of concept. I wish we had more people like you in codeproject. Thanks
Sergey Alexandrovich Kryukov 28-Sep-14 1:27am    
Correct, a 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900