动态开辟二维数组内存的问题

sure2003 2008-01-04 04:18:20

int *temp;
int m,n;
scanf("%d%d",&m,&n);
temp=(int *)malloc(m*n*sizeof(int));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);

malloc分配的地址空间是连续的,如果要以二维数组的方式去处理,好象这样编译不起来
怎么回事呢?大哥们?
...全文
263 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
sure2003 2008-01-04
  • 打赏
  • 举报
回复
a就是temp
ryfdizuo 2008-01-04
  • 打赏
  • 举报
回复
确实,sorry
^_^^_^
但是lz那样子做为了什么?
ltc_mouse 2008-01-04
  • 打赏
  • 举报
回复
呵呵,dizuo理解错了吧。
我也很奇怪为什么能编译通过,运行了下,才发现[i,j]其实只是个逗号表达式,^_^
ryfdizuo 2008-01-04
  • 打赏
  • 举报
回复

#include<iostream>
#include <cstdlib>
using namespace std;

int main()
{
int *temp;
int m,n;
printf("Input the m,n:");
scanf("%d%d",&m,&n);
temp=(int *)malloc(m*n*sizeof(int));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
printf("Input the data: ");
scanf("%d", &temp[i,j]); //好象直接这样子就可以的,
}
for (int i=0; i<m; i++)
for(int j=0; j<n; j++)
printf("%d ", temp[i,j]);

return 0;
}
ltc_mouse 2008-01-04
  • 打赏
  • 举报
回复
liln0530说的对,因而在已知一维数组长度的情况下,可以使用指向数组的指针:

int *temp;
const int n=3; //一维数组长度已知
int m;
int (*a)[n]; //指向数组的指针
scanf("%d",&m);
temp=(int *)malloc(m*n*sizeof(int));
a = (int(*)[n])temp;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
free(temp);
liln0530 2008-01-04
  • 打赏
  • 举报
回复
数组的存储方式也是连续的内存空间
ltc_mouse 2008-01-04
  • 打赏
  • 举报
回复
sorry,上面我给的a[i]错了,应该是a[i]=temp+n*i;
ltc_mouse 2008-01-04
  • 打赏
  • 举报
回复
是想用一维数组模拟二维吗?这样可以吗?

int *temp;
int m,n;
int **a;
scanf("%d%d",&m,&n);
a = (int **)malloc(m*sizeof(int *));
temp=(int *)malloc(m*n*sizeof(int));
for(int i=0;i<m;i++)
{
a[i] = temp+n;
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);
}

//...

free(a);
free(temp);
linlan999 2008-01-04
  • 打赏
  • 举报
回复
int *temp;
int m,n;
scanf("%d%d",&m,&n);
temp=(int *)malloc(m*n*sizeof(int));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf("%d",(tempa+i*m+j));


这样呢?
  • 打赏
  • 举报
回复
你的a[][]数组定义了吗?它和你动态开辟出来的内存没有关系。
你用&temp[i][j]试一下。
Treazy 2008-01-04
  • 打赏
  • 举报
回复

int *temp;
int m,n;
scanf("%d%d",&m,&n);
temp=(int *)malloc(m*n*sizeof(int));

for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf("%d", &tmp[i*m+j]);
Slin000 2008-01-04
  • 打赏
  • 举报
回复
因为系统不知道m和n, 也就是不知道你的数组每一维的大小
把 scanf("%d",&a[i][j]);
改为 scanf("%d",temp + i*m + j);
就可以为这个数组输入值
p0303230 2008-01-04
  • 打赏
  • 举报
回复
a跟temp什么关系?

70,037

社区成员

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

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