access violation with dynamic 2-dimension array in C++

Viewed 54

thanks you for being here to help
i want to have dynamic 2d dimension as char

int n;
char** stars;
 int main() {
    cin >> n;
    for (int i = 0;i < n;i++) {
        stars = new char* [n];
        stars[i] = new char[n];
        for (int j = 0;j < n;j++) {
            stars[i][j] = '*';
        }

    }
    for (int i = 0;i < n;i++) {
        for (int j = 0;j < n;j++) 
            cout << stars[i][j];   //this is where access violation is occured
        cout << endl;
    }
    return 0;
}

and i also want to know that if i put * on this array then new char data which contains '*' is generated on memory(maybe stack in this code) at each time it is inserted?

2 Answers
        stars = new char* [n];

is wrongly positioned in the loop, so you reallocate it per each string, and in the freshly allocated matrix only one string is allocated.

stars = new char* [n]; why would you declare this inside the for loop ? It is going to allocate again and again for every loop. just declare it outside

Related