Reputation: 1701
I'm trying to learn Pointers and References in C++. I have the following program.
#include <iostream>
using namespace std;
int main() {
// 1st statement / code of block. This portion works fine.
char *str = "A";
cout << str << endl; // it outputs A
cout << *str << endl; // it outputs A
cout << &str << endl; // it outputs 0x23fe40 (memory location)
char **b = &str;
cout << b << endl; // it outputs 0x23fe40 (memory location)
cout << *b << endl; // it outputs A
// 2nd statement / code of block. This portion gives error.
// int *st = 5;
// cout << st << endl;
// cout << *st << endl;
// cout << &st << endl;
// int **c = &st;
// cout << c << endl;
// cout << *c << endl;
return 0;
}
The code runs fine at this stage. but I run the 2nd statement (which I commented here), the compiler gives the following error.
Invalid conversion from 'int' to 'int*'
Can someone please explain why it happens? Both statements are almost same, the only difference is that I used data type 'int' in second statement. Is it because of the different data types?
Upvotes: 0
Views: 240
Reputation: 2291
As people mentioned before, with str you are implicitly creating a character array, and the *char pointer returned is pointing to that array in memory. Hence, when you dereference it, you get the letter "A".
One thing you should realize is that when you dereference a string, you will only get the first character in the array (the returned pointer points to the first value in the array). If your string were to be "AB" instead of just "A", *str would return "A" only, where as str would print out "AB".
This doesn't work for the integer variable because there is no implicit reference the variable is initializing to. An integer is a primitive and you can't dereference without a reference, and you can't retrieve a pointer without something to point to. This is why it couldn't convert an integer value to a pointer to an integer value.
Note that you can still declare a variable that contains a primitive value and obtain the address of it (&st will still work after declaration). If you want to play around with memory dereferencing with an int value, you can mess around with referencing other variables. E.g.
int i = 5;
int *st = &i;
int **c = &st;
the first variable will print out 5, the second will print out the address to the variable i, and the third will print the address of the pointer to the variable i.
Fun stuff. Basically just mess around to get a feel for pointers and such.
Upvotes: 2