Why pointer is not same | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why pointer is not same

Hi When we have pointer to int, we assing value to pointed variable by using astric like below: int i ;int* p = &i; *p = 5; But it is not the case for array as below : int* p = new int[20]; for(int i=0;i<20;++i) { p[i] = i; } Why *p[i] is not needed here ? https://code.sololearn.com/cS86FMTsOyLq/?ref=app

22nd Nov 2022, 9:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Answers
+ 3
You are creating a pointer for the array not for the array elements. What you're doing inside the loop is accessing the array elements. p holds the address of the array. So u can use the subscript operator. *p[i] means *(p[i]) --- here p[i] isn't a pointer. The pointer is for the whole array not for a particular element. I understand this but not sure if I'm explaining this correctly.
22nd Nov 2022, 11:10 AM
Kashyap Kumar
Kashyap Kumar - avatar
+ 1
1) you don't need asterix when accessing array members because the indexing [] operator is doing that for you. p[i] is equivalant to *(p+i) 2) as on the surface we only have a pointer to integer ( int *p ), you would need two different delete operator to seperately handle cases where the pointer is pointing to a single integer or an array of integers. 3) regarding that commented area of code : according to standards, if during a brace initialisation the compiler have to perform a narrowing conversion ( type conversion from higher type to a lower type like from double to int in your case ), the code should be considered ill-formatted and it's up to your implementation to throw a warning or error regarding the same.
23rd Nov 2022, 12:54 AM
Arsenic
Arsenic - avatar
+ 1
delete is used to de-allocate memory allocated for single object delete[] is used to de-allocate memory allocated for array of objects (just like you allocated memory using [])
23rd Nov 2022, 8:33 AM
Kashyap Kumar
Kashyap Kumar - avatar
0
Yeah i know there are two concepts for pointer and array together If it's just a pointer for array means only one pointer involved, why delete[] is needed instead of delete
22nd Nov 2022, 11:19 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Or my delete[] in code is wrong ?
22nd Nov 2022, 11:19 AM
Ketan Lalcheta
Ketan Lalcheta - avatar