| 编程中国 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛
全能ASP/PHP/ASP.NET主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付学习型 ASP/PHP/ASP.NET 主机 30元/年
高端软件开发 = 年薪十万不是梦赛孚耐:软件保护加密专家身份认证令牌USB KEY 
共有 217 人关注过本帖
标题:[求助]程序运行过程中出错
收藏  订阅  推荐  打印 
hegj
Rank: 1
等级:新手上路
帖子:30
积分:412
注册:2007-9-5
[求助]程序运行过程中出错

这是书中的一道练习题,我写了一个程序,编译通过了。但在运行时,系统提示出错,要关闭。
希望大家给我看看,对问题,对程序提提意见的。谢谢大家了!

给定如下的main()函数,该函数仿效在空闲存储区中创建二维数组,分别以rows和cols作为二维,
int main()
{
int **ptr;
int rows, cols;
while(!allocate(ptr, rows, cols))
{
fill(ptr, rows, cols);
display(ptr, rows, cols);
release(ptr, rows);
}
}
编写下面这些函数:
(1)allocate(),首先允许用户指定rows和cols参数值,然后分配一个指针数组,数组的
每个元素都指向一个ints数组(如果遇到文件结束标志,这个函数就返回flase);
(2)fill(),给行×列个数组元素赋值;
(3)display()输出所有数组元素;
(4)release(),释放所有从空间存储区中分配的空间。


我写的程序是这样的:


#include<iostream>
using std::cout;
using std::cin;

bool allocate(int **ptr, int &rows, int &cols);
void fill(int **ptr, int rows, int cols);
void display(int **ptr, int rows, int cols);
void release(int **ptr, int rows);

int main()
{
int **ptr;
int rows, cols;
while(!allocate(ptr, rows, cols))
{
fill(ptr, rows, cols);
display(ptr, rows, cols);
release(ptr, rows);
}
system("pause");
return 0;
}

bool allocate(int **ptr, int &rows, int &cols)
{
if(cin.eof()) return true;
cout << "Input the rows and cols:\n";
cin >> rows >> cols;
ptr = new int*[rows];
for(int i = 0; i < rows; ++i)
ptr[i] = new int[cols];
return false;
}

void fill(int **ptr, int rows, int cols)
{
cout<<"Input rows * cols ints:\n"; // 刚输出这个,系统就提示出错,每次都是这里

for(int i = 0; i < rows; ++i)
for(int j = 0; j < cols; ++j)
cin >> ptr[i][j];
}

void display(int **ptr, int rows, int cols)
{
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < cols; ++j)
cout << ptr[i][j] << '\t';
cout << '\n';
}
}

void release(int **ptr, int rows)
{
for(int i = 0; i < rows; ++i)
delete ptr[i];
delete ptr;
}

搜索更多相关主题的帖子: ptr  cols  rows  int  
2007-10-3 23:11
aipb2007
Rank: 12Rank: 12Rank: 12
来自:CQU
等级:贵宾
威望:40
帖子:2881
积分:29414
注册:2007-3-18

bool allocate(int **&ptr, int &rows, int &cols);

传值调用是对实参的一个copy,引用调用是实参本身。


Fight  to win  or  die...
2007-10-4 12:41
海子星竹
Rank: 2
等级:注册会员
威望:1
帖子:58
积分:722
注册:2007-9-4

刚看了下不知道怎么回事
看了版主的回答豁然开朗


还是版主厉害啊!!
2007-10-4 12:56
hegj
Rank: 1
等级:新手上路
帖子:30
积分:412
注册:2007-9-5

谢谢,我想明白了。
allocate()函数最终改成这样:
bool allocate(int **&ptr, int &rows, int &cols)
{
cout << "Input the rows and cols:\n";
if((cin >> rows >> cols).eof())
return true;
ptr = new int*[rows];
for(int i = 0; i < rows; ++i)
ptr[i] = new int[cols];
return false;
}

2007-10-4 13:25
关于我们 | 广告合作 | 编程中国 | 清除Cookies | Archiver | WAP | TOP

编程中国 版权所有,并保留所有权利。鲁ICP备08000592号
Powered by Discuz, Processed in 0.052385 second(s), 9 queries.
Copyright©2004-2008, BCCN.NET, All Rights Reserved