我是一名学生,我不得不承认我的指点有点薄弱,这就是为什么我得到这个练习来练习的原因。目前我的问题是我的程序在遇到 printf 时在 markMines() 函数中崩溃。我相信它是因为它读取了一个空值。我几乎尝试了所有我能想到的方法。我已经检查了问题从哪里开始以及我何时开始 *field = array;我已经在这里工作了几个小时,我需要一双新的眼睛来帮助我。另请注意,所有函数参数和 main() 均已设置,我无法更改它们。我在下面附加了我的代码。
int main(void)
{
int **mine=0;
int r,c;
initField(&mine,&r,&c);
markMines(mine,r,c);
return 0;
}
void initField(int ***field, int *rows, int *cols)
{
int r, c;
int FieldInput = 0;
int **array;
scanf("%d %d", &r, &c );
array = malloc((r)*sizeof(int));
*rows = r;
*cols = c;
for(r = 0; r < *rows; r++)
{
array[r] = malloc((c)*sizeof(int));
}
field =&array;
for(r = 0; r < *rows; r++)
{
for(c = 0; c < *cols; c++)
{
scanf("%d", &FieldInput);
array[r][c] = FieldInput;
}
printf("\n");
}
}
void markMines(int *const*const field, int rows, int cols)
{
int r = 0, c = 0;
for(r = 0; r <rows ; r++)
{
for(c = 0; c < cols ; c++)
{
printf("%d ", **field );
}
}
}
如有任何帮助,我将不胜感激。
最佳答案
功能完全无效。
程序可以通过以下方式定义。考虑到这些函数应该在它们在 main 中使用之前声明。
#include <stdlib.h>
#include <stdio.h>
void initField(int ***field, int *rows, int *cols);
void markMines( int *const*const field, int rows, int cols);
int main( void )
{
int **mine = 0;
int r, c;
int i;
initField(&mine,&r,&c);
markMines( mine, r, c );
for ( i = 0; i < r; i++ ) free( mine[i] );
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
free( mine );
//^^^^^^^^^^^
}
void initField(int ***field, int *rows, int *cols)
{
int r, c;
int FieldInput = 0;
int **array;
scanf("%d %d", rows, cols );
array = malloc( *rows * sizeof( int *) );
// ^^^^^^
for ( r = 0; r < *rows; r++)
{
array[r] = malloc( *cols *sizeof( int ) );
}
*field = array;
//^^^^^^^^^^^^^
for ( r = 0; r < *rows; r++ )
{
for ( c = 0; c < *cols; c++ )
{
scanf("%d", &FieldInput);
array[r][c] = FieldInput;
}
printf("\n");
}
}
void markMines( int *const*const field, int rows, int cols)
{
int r = 0, c = 0;
for(r = 0; r <rows ; r++)
{
for(c = 0; c < cols ; c++)
{
printf( "%d ", *( *( field + r ) + c ) );
// ^^^^^^^^^^^^^^^^^^^^^^^
}
printf( "\n" );
}
}
关于c - 无法访问我创建的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940070/