Dav*_*nce 1 c++ memory printing arrays
#include <iostream>
using namespace std;
int main(){
int findMax(int *);
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
int mval = findMax(values);
cout << values << endl << mval;
return 0;
}
//Function to find the maximum value in the array
int findMax(int arr[]){
int localmax = 0;
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
if(arr[i] > localmax){
localmax = arr[i];
}
}
return localmax;
}
Run Code Online (Sandbox Code Playgroud)
该程序的目的是让用户输入以空格分隔的一系列值,以0结尾.然后分析该数组以找到最大值.我想出了如何将原来的char []转换为int [],以便我可以在其上使用findMax()函数而不会出现错误,但排序循环似乎有自己的问题,当"cout <<值<< endl << mval;" 如果被调用,它只返回一个内存地址,而不是一个非间隔的整数序列.谁能解释我做错了什么?似乎我可能在使用指针时犯了一些错误,但我无法弄清楚是什么.
打印values不会按预期打印数组的内容,它将打印数组第一个元素的内存位置.
尝试这样的事情:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Run Code Online (Sandbox Code Playgroud)
对不起,我无法发布实际工作代码,但您的原始帖子是一堆乱七八糟的语法和语法错误.
编辑:为了让初学者更加完整,更容易理解和理解,我写了一个小程序,说明了实现这一目标的4种方法.
方法1使用copy与ostream_iterator我之前所做的那样.下面的方法2可能是最基本和最容易理解的.方法3是C++ 0x方法.我知道问题是标记为C++,但我认为添加它可能是有教育意义的.方法4是使用vector和的C++方法for_each.我已经实现了一个执行转储的仿函数.
分享和享受
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct dump_val : public unary_function<int,void>
{
void operator()(int val)
{
cout << val << " ";
}
};
int main(){
int vals[5] = {1,2,3,4,5};
// version 1, using std::copy and ostream_iterator
copy(&vals[0], &vals[5], ostream_iterator<int>(cout, " "));
cout << endl;
// version 2, using a simple hand-written loop
for( size_t i = 0; i < 5; ++i )
cout << vals[i] << " ";
cout << endl;
// version 3, using C++0x lambdas
for_each(&vals[0], &vals[5], [](int val)
{
cout << val << " ";
}
);
cout << endl;
// version 4, with elements in a vector and calling a functor from for_each
vector<int> vals_vec;
vals_vec.push_back(1);
vals_vec.push_back(2);
vals_vec.push_back(3);
vals_vec.push_back(4);
vals_vec.push_back(5);
for_each( vals_vec.begin(), vals_vec.end(), dump_val() );
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)