c - C中的动态内存分配二维数组

标签 c arrays pointers dynamic

<分区>

int **twoDary = (int**) (malloc(rows * sizeof(int *)));
int **twoDaryStart = twoDary;
int *currentrow;

for ( i = 0; i < rows; i++ ){  // Originally: for (i = 0; i < columns; i++)
    *(twoDary + i) =  (malloc(columns * sizeof(int)));
}

for (j = 0; j < rows; j++) {
    currentrow = *(twoDary + j);
    for ( i = 0; i < columns; i++ ) {
        *(currentrow + i) = i;
        printf("%d\n", *(currentrow+i));
    }
}  

我正在尝试创建一个动态二维数组。然后我试图将 i ,当前 i (在内部 for 循环中)分配给每一行中的每个元素。所以我的输出应该是数字 0 - 列打印的行时间。

如果我的行和列不相同,即 5 行 10 列,我会不断收到段错误。谁能从这段代码中看出为什么会发生这种情况?

最佳答案

你的第一个循环应该是:

for (i = 0; i < rows; i++)
{
    ...
}

显然代码是一致的(但错误)——同样的问题出现在 free() 代码中。这是我的 SSCCE对于这个问题。 valgrind给它一份干净的健康证明.

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

extern int **alloc_array(int rows, int columns);

int **alloc_array(int rows, int columns)
{
    int i;
    int j;
    int **twoDary = (int**) (malloc(rows * sizeof(int *)));
    int **twoDaryStart = twoDary;
    int *currentrow;

    for ( i = 0; i < rows; i++ ){
        *(twoDary + i) =  (malloc(columns * sizeof(int)));
    }

    for (j = 0; j < rows; j++) {
        currentrow = *(twoDary + j);
        for ( i = 0; i < columns; i++ ) {
            *(currentrow + i) = i;
            printf("%d\n", *(currentrow+i));
        }
    }  
    return twoDary;
}

int main(void)
{
    int **d2 = alloc_array(5, 10);

    for (int i = 0; i < 5; i++)
        free(d2[i]);
    free(d2);
    return(0);
}

关于c - C中的动态内存分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14698656/

相关文章:

C 访问结构中的元素

c - 如何在 C 中将字符串添加到 PUNICODE_STRING 的末尾

c# - P/Invoke 调用中的 AccessViolationException

c++ - 强制转换为 void* 以将对象传递给 C++ 中的 pthread

c - 使用 void 指针将 float 存储到数组中

python - Python 的 set() 在 C 中是否有等价物?

c - 错误 : subscripted value is neither array nor pointer nor vector Need for class

JavaScript push() 问题

c - 使用结构搜索并匹配数组元素

c - 检测传递指向未初始化变量的指针