2D阵列动态内存分配崩溃 [英] 2D array dynamic memory allocation crashes

查看:114
本文介绍了2D阵列动态内存分配崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我正在尝试使用calloc为2D数组动态分配内存。列固定为2,因此只有动态的行。

I am trying to dynamically allocate memory for a 2D array using calloc. The columns are fixed as 2 so its only the rows that are dynamic.

这是我一直在尝试的内容:

Here is what I have been trying :

unsigned int **pts, rows;
int main()
{
    //some code

    pts = (unsigned int **)calloc(2*rows, sizeof (unsigned int **));
}


//The code to access the array :
for(k=1;k<=i;k++)
{
    printf("\nX%d=",k);
    scanf("%d",&pts[k][0]);
    printf("\nY%d=",k);
    scanf("%d",&pts[k][1]);
}

但是问题是,在访问数组时,程序崩溃了。
我正在将Eclipse与MinGW GCC配合使用。

But the problem is, while accessing the array, the program crashes. I am using Eclipse with MinGW GCC.

请告诉我是否需要在此处放置更多数据,或者告诉我如何处理此问题,因为这是我的第一篇文章。

Please let me know if I need to put more data here or give me some idea how I can deal with this, as this is my first post.

推荐答案

都铎王朝的答案是正确的解决方案。
但是要提供更多关于您的代码为什么出错的见解...。

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

您实际创建的内容是:

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

然后您尝试为一个 null分配一个整数 int **数组中零初始化的 int *所指向的em>地址(您可以看到,calloc已确保所有 int *为零)

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)

当您尝试执行时

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

pts [k]指的是数组中的第(k-1)个元素int **,但如上所述,尽管您的代码确实为该元素分配了空间,但已将其初始化为零。因此,此pts [k]指向NULL。因此scanf已经获得了一个基于NULL地址零偏移量的地址...现在您应该清楚这是无效的。

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.

这篇关于2D阵列动态内存分配崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆