Hello, I have a question about pointer initialization. I do not know if this question has been asked before but I searched and can not find. I have read in the documentation: "As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared:
char * terry = "hello";
But my question is if this is only possible with char type or it is also possible with another type, since I have written this piece of code to check..
int main()
{
int * puntero = 415;
cout << puntero;
cout << *puntero;
}
but the compiler said me:
error : invalid conversion from 'int' to 'int*' and focuses the line
int * puntero = 415;
Remember that char is a single character. You are giving it a string (multiple characters). What is actually happening is that terry only points to the 'h' in "hello". It's similar to this:
1 2 3
char abuffer[] = {'h','e','l','l','o',0};
char* terry = abuffer; // points to the first element in the array
You can test this by doing the following:
cout << *terry; // this will only print 'h', not the full "hello" string
You can do this with ints also:
1 2 3 4 5
int intbuffer[] = {1,2,3,4,5};
int* ptr = intbuffer;
cout << *ptr; // prints "1"
C++ just allows the direct assigning of string literals as a convenience.
It's only possible with char * and wchar_t *. That's because string literals are translated by the compiler into pointers:
1 2 3
//(The explicit cast to void * ensures that the memory address will be printed,
//rather than the string at that memory address.)
std::cout <<(void *)"hello";
Note that your string pointer is incorrect, though. The proper way to declare a pointer to a string literal is constchar *terry="hello";
Thank you very much! I understood ! . but just one more thing, about helios' answer. What if I do not want the char pointer was constant, the statement would be ok?
constchar * defines a variable pointer to a constant char, not a constant pointer to a variable char. This is the correct way to declare a pointer to a string literal, because the way you're doing it now, the compiler will let you do this:
1 2
char * terry = "hello";
terry[0]='H';
But the program will crash when you try to run it.
However, if you try to do this:
//Allocates an array of size 6 on the stack and copies to it the contents of "hello".
char modifiable_string[]="hello";
char *variable_pointer_to_variable_char=modifiable_string;