Segmentary fault with pointer array C++

  arrays, c++, pointers

I get Segmentary fault with this code:

 #include <iostream>
    
    using namespace std;
    
    int* arrayCreate(int length){
        int *ew[length];
        for (int i=0; i<length; i++)
        {
            *(ew[i])=i;
        }
    
        return ew[0];
    }
    
    int main(){
        int *ptr=arrayCreate(7);
        cout << *ptr << endl;
    }

And when I tried to change this line

int *ew[length];

into

int *ew = new int[length];

I have error < indirection requires pointer operand (‘int’ invalid) >

Any one please explain the difference between these two declaration, why I get segmentary fault and how to fix it?

Source: Windows Questions C++

LEAVE A COMMENT