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.