我的工作我的有关动态分配学生的项目,我想我有我发送一个问题,有人能帮忙吗?
void buildBoard(int*** mat, int size);
void initMat(int*** mat, int size);
int main()
{
int size;
int** mat;
printf("Please enter a size of the matrix:\n");
scanf("%d", &size);
buildBoard(&mat, size);
initMat(&mat, size);
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
return 0;
}
void buildBoard(int*** mat, int size)
{
*mat = (int**)malloc(size * sizeof(int*));
if (*mat == NULL)
{
printf("Bye\n");
exit(1);
}
for (int i = 0; i < size; ++i)
{
mat[i] = (int*)malloc(size * sizeof(int));
if (mat[i] == NULL)
{
printf("Bye\n");
free(mat[i]);
}
}
}
void initMat(int*** mat, int size)
{
int num;
printf("Please enter a numbers:\n");
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
scanf("%d", &mat[i][j]);
}
}
}
在主函数中我想看看我的配置,它崩溃的所有打印时的时间。
你错过了提领垫好几次,我的意思是一些mat
必须(*mat)
:
void buildBoard(int*** mat, int size)
{
*mat = (int**)malloc(size * sizeof(int*));
if (*mat == NULL)
{
printf("Bye\n");
exit(1);
}
for (int i = 0; i < size; ++i)
{
(*mat)[i] = (int*)malloc(size * sizeof(int));
if ((*mat)[i] == NULL)
{
printf("Bye\n");
exit(1);
}
}
}
void initMat(int*** mat, int size)
{
printf("Please enter a numbers:\n");
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
scanf("%d", &(*mat)[i][j]);
}
}
}
我也删除无用的变量num
编译和执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
Please enter a size of the matrix:
2
Please enter a numbers:
1
2
3
4
1 2
3 4
在Valgrind的:
pi@raspberrypi:/tmp $ valgrind ./a.out
==4232== Memcheck, a memory error detector
==4232== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4232== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4232== Command: ./a.out
==4232==
Please enter a size of the matrix:
2
Please enter a numbers:
1
2
3
4
1 2
3 4
==4232==
==4232== HEAP SUMMARY:
==4232== in use at exit: 24 bytes in 3 blocks
==4232== total heap usage: 5 allocs, 2 frees, 2,072 bytes allocated
==4232==
==4232== LEAK SUMMARY:
==4232== definitely lost: 8 bytes in 1 blocks
==4232== indirectly lost: 16 bytes in 2 blocks
==4232== possibly lost: 0 bytes in 0 blocks
==4232== still reachable: 0 bytes in 0 blocks
==4232== suppressed: 0 bytes in 0 blocks
==4232== Rerun with --leak-check=full to see details of leaked memory
==4232==
==4232== For counts of detected and suppressed errors, rerun with: -v
==4232== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@
当然Valgrind的显示内存泄漏,因为你不释放分配的内存
请注意,这是没用的,给予可变进initMat的地址,可以是:
void initMat(int** mat, int size)
{
printf("Please enter a numbers:\n");
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
scanf("%d", &mat[i][j]);
}
}
}
当然也改变其声明,并在主通话
以前我也删除你有免费的:
if (mat[i] == NULL)
{
printf("Bye\n");
free(mat[i]);
}
因为其实你免费NULL