您的阵列具有自动存储持续时间,并且一旦返回areas
就会超出范围;area
那么取消引用pointer
是未定义的行为。请使用 C++ 习惯用法,例如std::string
andstd::vector
而不是 C 指针。
这是您的代码的改进(但仍不是最佳)版本:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstddef>
std::vector<double> area(const std::vector<double>& radius)
{
std::vector<double> areas(radius.size());
for (std::size_t i = 0; i < radius.size(); i++) {
areas[i] = 3.1416 * radius[i] * radius[i];
}
return areas;
}
void print(const std::vector<double>& radius, const std::vector<double>& area)
{
for (std::size_t i = 0; i < radius.size(); i++) {
std::cout << area[i]; //This doesn't
std::cout << "Area for " << radius[i] << " is: " << area[i] << std::endl;
}
}
int main(int argc, char* argv[])
{
if (argc > 1) {
std::vector<double> radii;
radii.reserve(argc - 1);
for (int i = 1; i < argc; ++i) {
radii.push_back(std::atof(argv[i]));
}
print(radii, area(radii));
}
}
不幸的是,编译器通常无法检测到此类错误。使用 Valgrind 之类的工具来找到它们。例如,通过 Valgrind 运行您的原始代码会给我带来很多错误:
$ valgrind ./a.out 1 4 2 7 8
==18488== Memcheck, a memory error detector
==18488== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==18488== Using Valgrind-3.8.0 and LibVEX; rerun with -h for copyright info
==18488== Command: ./a.out 1 4 2 7 8
==18488==
==18488== Conditional jump or move depends on uninitialised value(s)
==18488== at 0x4EC5D16: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_int<long>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, long) const (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x4EC5F4C: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, long) const (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x4EC8E45: std::ostream& std::ostream::_M_insert<long>(long) (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x400A01: print(char**, int*, int) (in /tmp/a.out)
==18488== by 0x400B0E: main (in /tmp/a.out)
==18488==
==18488== Use of uninitialised value of size 8
==18488== at 0x4EBB133: ??? (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x4EC5D37: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_int<long>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, long) const (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x4EC5F4C: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, long) const (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x4EC8E45: std::ostream& std::ostream::_M_insert<long>(long) (in /usr/lib/libstdc++.so.6.0.17)
==18488== by 0x400A01: print(char**, int*, int) (in /tmp/a.out)
==18488== by 0x400B0E: main (in /tmp/a.out)
[…]
而我的版本没有产生错误。