#include <iostream>
int main()
{
// char array
char name1[] = "Hello";
std::cout << "name1 = " << name1 << std::endl;
std::cout << "&name1 = " << &name1 << std::endl;
std::cout << "*name1 = " << *name1 << std::endl;
std::cout << "name1[0] = " << name1[0] << std::endl;
std::cout << "&name1[0] = " << &name1[0] << std::endl << std::endl;
// char
const char* name2 {"World"};
std::cout << "name2 = " << name2 << std::endl;
std::cout << "&name2 = " << &name2 << std::endl;
std::cout << "*name2 = " << *name2 << std::endl;
std::cout << "name2[0] = " << name2[0] << std::endl;
std::cout << "&name2[0] = " << &name2[0] << std::endl;
}
Both ways of implementing – char array and char pointer gives same result.
- Are array of characters stored into array of pointers pointing to each character in the array?
- Why does
name1
returnHello
, in case of int, it returns address. name1[0]
returnH
but why does&name1[0]
returnHello
? Should it not return address of ‘H’ if ‘H’ is stored in separate memory location?- What is the difference in the two ways of implementing?
- Why do we need to have mandatory ‘const’ before char* ( C++20 compiler error on Visual Studio if const is not used)
Tried the two ways and confused why do they return the same result and different from array of int or pointer to int.
name1 = Hello
&name1 = 00000078C1FEFBA4
*name1 = H
name1[0] = H
&name1[0] = Hello
name2 = World
&name2 = 00000078C1FEFBC8
*name2 = W
name2[0] = W
&name2[0] = World
New contributor
User329 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2