输出数组出现奇怪结果,求解释

theillusion 2012-05-26 06:10:38
代码和输出如下,求解释:



#include <iostream>

using std::cout;
using std::endl;
using std::ostream;
using std::pair;
using std::make_pair;

// 记录
struct record
{
int key;
char data;

void output(ostream &out) const
{
out << key << ", " << data;
}
};

// 将记录输出到 cout
void output_records(const record *arr, size_t size)
{
for (size_t i = 0; i < size; ++i)
{
arr[i].output(cout);
cout << endl;
}
}

pair<record *, size_t> new_array()
{
const size_t size = 10;
record arr[size] =
{
{ 0, 'A' }
, { 1, 'B' }
, { 2, 'C' }
, { 3, 'C' }
, { 3, 'E' }
, { 5, 'F' }
, { 6, 'G' }
, { 7, 'H' }
, { 8, 'I' }
, { 9, 'J' }
};

return make_pair(arr, size);
}

int main()
{
auto arr_info = new_array();
output_records(arr_info.first, arr_info.second);

/*
输出:
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
*/

system("pause");
return 0;
}
...全文
174 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
theillusion 2012-05-26
  • 打赏
  • 举报
回复
明天结贴
theillusion 2012-05-26
  • 打赏
  • 举报
回复
确实是局部对象的问题
pathuang68 2012-05-26
  • 打赏
  • 举报
回复
pair<record *, size_t> new_array()这个函数有问题,原因:试图将栈上局部数组,作为返回值。

将record arr[size]改为static record arr[size]即可,或者
将arr设为全局数组,或者
用new或则malloc在堆上为其分配内存(这种方式要记得delete或者free)

無_1024 2012-05-26
  • 打赏
  • 举报
回复
还是先前说的传值的问题
record arr[size] =
{
{ 0, 'A' }
, { 1, 'B' }
, { 2, 'C' }
, { 3, 'C' }
, { 3, 'E' }
, { 5, 'F' }
, { 6, 'G' }
, { 7, 'H' }
, { 8, 'I' }
, { 9, 'J' }
};
这个地方是局部变量 当你除了这个函数以后就被析构了 所以输出是那些乱东西
建议 1.可以用new 来动态分配
2.就是static变量

#include <iostream>

using std::cout;
using std::endl;
using std::ostream;
using std::pair;
using std::make_pair;

// 记录
struct record
{
int key;
char data;

void output(ostream &out) const
{
out << key << ", " << data;
}
};

// 将记录输出到 cout
void output_records(const record *arr, size_t size)
{
for (size_t i = 0; i < size; ++i)
{
arr[i].output(cout);
cout << endl;
}
}

pair<record *, size_t> new_array()
{
const size_t size = 10;
static record arr[size] =
{
{ 0, 'A' }
, { 1, 'B' }
, { 2, 'C' }
, { 3, 'C' }
, { 3, 'E' }
, { 5, 'F' }
, { 6, 'G' }
, { 7, 'H' }
, { 8, 'I' }
, { 9, 'J' }
};
return make_pair(arr,size);
}

int main()
{
auto arr_info = new_array();
output_records(arr_info.first, arr_info.second);

/*
输出:
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
-858993460,
*/

system("pause");
return 0;
}
無_1024 2012-05-26
  • 打赏
  • 举报
回复
我好像看错了 我再看看 刚看懂你的题目意思
你的数组和record*之间是不能够之间转换的 没有分配空间
無_1024 2012-05-26
  • 打赏
  • 举报
回复
容器还要多看点
make_pair(arr, size);
产生的只有一个pair
而按照你的意思需要的是一个pair数组
所以你的问题很多 建议重新看看pair是干啥的在写
theillusion 2012-05-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

传值方式不对
[/Quote]

具体点
無_1024 2012-05-26
  • 打赏
  • 举报
回复
传值方式不对

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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