我是一名计算机科学专业的学生,并参加了我的第一堂C++课程。我很难理解我的代码是怎么回事:
// This program uses the address of each element in the array.
#include <iostream>
using namespace std;
int main()
{
const int NUM_COINS = 5;
int coins[NUM_COINS] = {5, 1, 25, 5, 10};
int *p1; // Pointer to a double.
int count; // Counter variable.
// Use the pointer to display the values in the array.
cout << "Here are the values in the coins array: \n";
for(count = 0; count << NUM_COINS; count++)
{
// Get the address of an array element
p1 = &coins[count];
// Display the contents of the element
cout << *p1;
}
cout << endl;
return 0;
}
g++ -c -o 9-8.o 9-8.cpp cc 9-8.o -o 9-8未定义符号:"std::basic_ostream >& std::operator<< (std::basic_ostream >& char const*)",引用自:_main in 9-8.o _main in 9-8.o "std::ios_base::Init::Init()",引用自:__static_initialization_and_destruction_0(int,int),在9-8.o中
"std::basic_string,std:size() const",引用于:std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)中的9-8.o "std::basic_string,std::allocator ::operatorunsigned long const",引用自:std::__verify_grouping( const*,未签名),std::basic_string,std::分配器>const&)在9-8.o std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)中9-8.o std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)在9-8.o "___gxx_personality_v0“中,参考来源: std::__verify_grouping(char const*,unsigned long,std::basic_string::allocator> const&)in 9-8.o ___tcf_0 in 9-8.o _main in 9-8.o(Int)在9-8.o全局构造函数中,在9-8.o "std::ios_base::Init::~Init()“中键为mainin 9-8.ocie,引用为:___tcf_0 in 9-8.o "std::basic_ostream >& std::endl (std::basic_ostream >&)",引用来源:_main in 9-8.o "std::basic_ostream ::operator<<(std::basic_ostream >& (std::basic_ostream>&)“),引用于:_main in 9-8.o "std::basic_ostream ::operator<<(int)",引用于:_main in 9-8.o "std::cout",引用来源:_main in 9-8.o _main in 9-8.o _main in 9-8.ld:符号collect2: ld返回1退出状态:* 9-8错误1
这引出了我的第二个问题。即使我输入了g++命令,它也会编译,但是在运行之后,它会输出一个空数组。所以我的第二个问题是:我的代码正确吗?如何在引用地址语句中正确使用指针?
发布于 2011-04-30 06:39:16
原因:您没有正确地使用比较操作符。在将其更改为"<“之后,您的代码应该正确工作。
for(count = 0; count << NUM_COINS; count++)
^ should be "<" here
发布于 2011-04-30 06:41:36
除了for
循环中的一个问题之外,我没有看到任何问题:
for(count = 0; count << NUM_COINS; count++)
//^^
这不是比较。那是左转操作。我相信你不是故意的。
应该是:count < NUM_COINS
。
https://stackoverflow.com/questions/5840064
复制相似问题