Search code examples
c++arrayspointersnew-operatordynamic-memory-allocation

Why this assignment is correct while it looks like assigning an int to int*?


The second assignment gives an error (a value of type "int" cannot be assigned to an entity of type "int *"), why isn't the same error showing up for the first assignment?

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int* x = new int[100];
    x[5] = 3;

    int* y[100];
    y[5] = 3;

    return 0;
}

Solution

  • x is of type pointer to int and y is of type array of 100 pointers to int.

    Then, x[0] is of type int& (reference to int) and y[0] is of type int*& (reference to pointer to int).

    Thus x[0] = 5 is assigning int value to int reference (perfectly valid), but y[0] = 5 is trying to assign int value to a pointer, which is not valid.