Like I encountered this doubt while learning dynamic memory allocation in C++, and just can't focus anymore on learning it now. :(
int n;
cout << "Enter array size: ";
cin >> n;
int *p = new int[n];
So everything is fine till now, I just allocated n blocks of int memory in heap area
Now, while taking the input using a for loop, I had this doubt while I tried to write p[i] as *(p+i)
for (int i = 0; i < n; i++)
{
// cin >> p[i]; // This is correct
// cin >> *(p+i); // This is correct
cin >> (p + i); // same as cin >> &p[i], right? Now, this gives me error since I didn't deference
// it and now I'm confused as to why we need to deference it? *(p+i) tells which
// block the value is to be stored in, but doesn't (p+i) also give us the same
// address? The input value should still have been stored in the respective memory
// block, right? But it doesn't and I can't visualize it why?
// Also, now I'm even confused as to why writing cin >> n works and writing cin >> &n doesn't??
}
I was simply expecting that my value should still be accepted into the respective array element, but it didn't, rather it gave me a very very wrong error, which I'm unable to understand.
I tried looking for answers, but still unclear with the concept visualization and clarity. All I've known so far is that cin is an object of istream class, >> operator while used with cin is kind of like a function call, and the variable name which we write after the >> operator is "passed by reference" or something like that, which might seem like that is why maybe we don't give address as reference variable already has it by default, but I'm not sure and still in doubt.
Please someone explain it in proper sequence and with proper example. I'll be grateful.
Type of
*(p + i)isintand type of(p + i)isint*. With the first one you are reading an integer, so that is clear.Why doesn't
cin >> (p + i)readint? When a function takes parameter by reference, the parameter must be the same exact type. You are giving itint*, so it will try to readint*.How would we read a pointer? I guess we could read an integer and assign it to the pointer variable. We are currently reading to the temporary value
p + i.operator>>needs a reference, which it cannot get for a temporary value, which is why you get a compile error.Let us skip this problem by using another variable:
This still does not compile, because there is an overload for reading
void*, but notint*. In C++, you cannot automatically convert between two pointer types. If you want to readint*, you can do that, but you have to write an overload foroperator>>.