2D动态分配内存错误

时间:2018-12-16 10:49:50

标签: c arrays 2d dynamic-memory-allocation nullptr

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    int sizestr, sizecol, **arr;
    printf("Sizestr is ");
    scanf_s("%d", &sizestr);
    printf("Sizecol is ");
    scanf_s("%d", &sizecol);
    arr = (int**)calloc(sizestr, sizeof(int*)); //creates 1d array of *int
    if (arr == NULL) {                          // checks allocation of memory
        printf("Error!\n");
        system("pause");
        return 1;
    }
    for (int i = 0; i < sizecol; i++) {
        *(arr + i) = (int*)calloc(sizecol, sizeof(int)); // creates 2nd d array of int
        if (*(arr + i) == NULL) {                        // checks every line for memory allocation
            printf("Error!\n");
            system("pause");
            return 1;
        }
    }
    for (int i = 0; i < sizestr; i++) {
        for (int j = 0; j < sizecol; j++) {
            printf("*(*(arr + %d) + %d) is ", i, j);
            scanf_s("%d", (*(arr + i) + j));            //scans every argument
        }
        printf("\n");
    }
    for (int i = 0; i < sizestr; i++) {
        for (int j = 0; j < sizecol; j++) {
            printf("%3d ", *(*(arr + i) + j));           //prints every argument
        }
        printf("\n");
    }
    system("pause");
    return 0;
}

此代码创建用户选择的二维数组大小。它适用于每个数字(如果有字符串)和列的每个数,但是当我设置列1时,它会在第二个参数中崩溃,并带有错误“ result_pointer!= nullptr”。

0 个答案:

没有答案