简体   繁体   中英

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

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?

        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM