二维动态数组的内存分配错误

蓝莓派Alex 2018-08-16 05:21:50
//申请二维动态数组
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef int DataType;
//二维数组申请函数
int **ApplyTwo( int row, int col)
{
DataType **array;
int i;

if ((array=(DataType**)malloc(row*sizeof(DataType*)))==NULL) //分配行的空间
{
printf("0error");
exit(0);
}
for ( i = 0; i < row; i++) //在每一行分配列的空间
{
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);
{
printf("1error");
getchar();
exit(0);
}
}
return array;
}
//销毁内存空间
DestroyMem(DataType **array,int row)
{
int i;
for ( i = 0; i < row; i++)
{
free(array[i]); //先逐个释放行的内存。
}
free(array); //在释放指向一维数组的内存。
}

//主函数
int main()
{
DataType **s;
int i,j,c=1;
int row = 3, col = 5;
s=ApplyTwo(row, col);
for ( i = 0; i < row; i++)
{
for ( j = 0; j < col; j++)
{
s[i][j] = c;
c++;
}
}
for ( i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d ", s[i][j]);
}
printf("\n");
}
DestroyMem(s, row);
system("pause");
return 0;
}
...全文
197 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
蓝莓派Alex 2018-08-16
  • 打赏
  • 举报
回复
当局者迷旁观者清。
引用 2 楼 sghcpt 的回复:
在int **ApplyTwo( int row, int col)函数中的下面代码:
 if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);

再最后面多了一个分号,把分号去掉试试~~~~~~~~~应该改为如下代码:
 if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL)
蓝莓派Alex 2018-08-16
  • 打赏
  • 举报
回复
学习而已,没必要用库函数。
引用 1 楼 Slzde_sub 的回复:



#include<vector>
using std::vector;

vector<vector<int>> vecValueArray;


这不就完事了吗。。。你写了一大堆还怕错
自信男孩 2018-08-16
  • 打赏
  • 举报
回复
if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);

注意这条语句的后面多一个分号
sghcpt 2018-08-16
  • 打赏
  • 举报
回复
在int **ApplyTwo( int row, int col)函数中的下面代码:
 if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL);

再最后面多了一个分号,把分号去掉试试~~~~~~~~~应该改为如下代码:
 if ((array[i] = (DataType *)malloc(col * sizeof(DataType))) == NULL)

70,021

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧