char s* and char s[]

Dec 21, 2011 at 11:11am
Code:
#include <iostream>
using namespace std;

void main()
{
char *s="hello";

cout << &s << endl;
cout << static_cast<void*>(s) << endl;
cout << (void*)s << endl;


char cs[]="hello";

cout << &cs << endl;
cout << static_cast<void*>(cs) << endl;
cout << (void*)cs << endl;
}

Questions:

why &cs won't give the address of the pointer which store the starting address
of the cstring cs?
is it because the addressof operator is overloaded to directly return the address of the cstring?

does the first way (char *s) of creating cstring allocate memory in the heap?
or both method allocate memory in the stack?

Thx
Last edited on Dec 21, 2011 at 11:33am
Dec 21, 2011 at 12:24pm
cs is an array so &cs gives you a pointer to the first element in the array.

char *s="hello"; Here s is a pointer to the string. Only the pointer is allocated on the "stack". To be strict it should const char *s="hello"; because you are not allowed to change what s is pointing to.

char cs[]="hello"; This creates the array on the "stack".
Topic archived. No new replies allowed.