Sys*_*Fun 2 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));
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个动态的二维数组.然后我尝试将i,当前i(在内部for循环中)分配给每一行中的每个元素.所以我的输出应该是数字0 - 列打印行时间.
如果我的行和列不相同,即5行10列,我会一直遇到seg错误.任何人都可以从这个代码中看到为什么会发生这种情况?
你的第一个循环应该是:
for (i = 0; i < rows; i++)
{
...
}
Run Code Online (Sandbox Code Playgroud)
显然代码是一致的(但是错误的) - 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);
}
Run Code Online (Sandbox Code Playgroud)