2D array dynamic memory allocation crashes [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-02 03:10:42

Tudor's answer is the correct solution. But to provide a bit more insight into why your code is wrong....

What your code is really doing is just to allocate an array, of length 2 * rows, of pointer to pointer to type int.

What you are trying to create is this:

an array of int** -> int* -> int
                          -> int
                          -> int
                          -> ...more
                  -> int* -> int
                          -> int
                          -> int
                          -> ...more
                  -> int* -> int
                          -> int
                          -> int
                          -> ...more
                  -> ...more

What you have actually created is this:

an array of int** -> int* -> nothing (null address)
                  -> int* -> nothing...
                  -> ...more

You then attempt to assign an int to one of the null address pointed by one of the zero-initialized int* in your array of int** (You see, calloc has made sure that all your int*'s are zero)

When you are trying to execute

scanf("%d",&pts[k][0]);

pts[k] refers to the (k - 1)th element in your array of int**, but as shown above, though your code has allocated space for this element indeed, it has initialized it as zero. So, this pts[k] points at NULL. So scanf has obtained an address based on a zero offset from the NULL address... It should be now clear to you that this is invalid.

Here's the way to do it:

pts = (unsigned int **)calloc(rows, sizeof (unsigned int *));
for(int i = 0; i < rows; i++) {
    pts[i] = (unsigned int *)calloc(2, sizeof (unsigned int));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!