Segmentation fault: 11; range-based for loop - c++

I'm working on a small programming exercise in C++. Goal is to initiate an array with the first 32 exponentations of 2 and to output them afterwards.
Using a normal for loop there's no problem but I tried to use the range-based for loop introduced in the C++11 standard.
During compilation I get the warning "range-based for loop is a C++11 extension [-Wc++11-extensions]".
Running the program I get the error "Segmentation fault: 11" without any further output.
I got already that the elem variable somehow is broken but I don't know how.
Hope you can help a n00b :)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int LAENGE = 32;
long potenzen[LAENGE];
for(int elem : potenzen)
{
potenzen[elem] = pow(2.0, (double) (elem + 1));
}
for(int elem : potenzen)
{
cout << endl;
cout << potenzen[elem];
}
cout << endl;
return 0;
}

elem is assigned the values in potenzen, not indices. cout << elem; is what you want instead to print the elements of the array. And in order to fill the array, simply use integer indices:
for (int i = 0; i < LENGTH; i++) { // ProTip #1: use English identifiers
array[i] = 2 << i; // ProTip #2: don't use `pow()` when working with integers
}
As to the compiler warning: use the -std=c++11 or -std=c++0x flag when compiling to tell the compiler you are intending to use C++11 features (assuming you use GCC or clang -- I'm not sure about other compilers.)

Ranged for loop wil give you element values, and not the element indices.
potenzen[elem] = pow(2.0, (double) (elem + 1));
should be
for(int i = 0; i < LAENGE; i++)
potenzen[i] = 2 << i;
(For shifting, refer to the H2CO3's answer and to the his comments below)
Note that you can't use foreach loop here:
for(int& elem : potenzen)
{
elem = pow(2.0, (double) (elem + 1));
}
as you're accessing not-initialized value of elem in the right side of the statement.
Also:
for(int elem : potenzen)
{
cout << endl;
cout << potenzen[elem];
}
Should be
for(int elem : potenzen)
{
cout << endl;
cout << elem;
}
as elem will contain array values.

The above answers rightly point out the issues in your code, however if you want to have array indices as element values you've to set them up, without which they'd be initialized to indeterminate (garbage) values; the following code is also a solution that's somewhat similar to what you tried to do:
#include <iostream>
#include <algorithm>
int main()
{
constexpr auto count = 32;
unsigned long long values[count] = { }; // initialise elements to 0
auto i = 0;
// fill them with their respective index values
std::generate_n(values, count, [&i] { return i++; });
for(auto &x : values)
{
// without casting the literal 2 would be treated as an int
x = static_cast<unsigned long long>(2) << x;
std::cout << x << std::endl;
}
return 0;
}
I've used unsigned long long instead of long, since on many systems the size of a long is 4 bytes, but 2^32 = 4294967296 = 0x100000000 I.e. 33 bits are required. Also since we know that all values are going to be positive, making it unsigned makes more sense.

Related

How to output the maximum value inside an array

#include <iostream>
using namespace std;
void value(int array[],int size){
int minimum;
int maximum;
minimum = array[0];
for(int x = 0; x < size; x++){
if(minimum > array[x+1]){
minimum = array[x+1];
}
}
maximum = array[0];
for(int x = 0; x < size; x++){
if(maximum < array[x+1]){
maximum = array[x+1];
}
}
cout << "Minimum Value is: " << minimum << endl;
cout << "Maximum Value is: " << maximum;
}
int main(){
int size;
cout << "Number of values you want to input: ";
cin >> size;
cout << "Input " << size << " values" << endl;
int array[size];
for(int x = 0; x < size; x++){
cout << "Input #" << x+1 <<": ";
cin >> array[x];
}
value(array,size);
return 0;
How can I output the maximum value inside the array? whenever I print the value the maximum value always return a number that is not present inside the array but the minimum seems fine, its only the maximum value that I am encountering a problem, I tried every possible answer that I know but it doesn't work, I hope ya'll can help Thank you in advance
for(int x = 0; x < size; x++){
If you have an array with ten values, size will be 10. If you work out, with paper and pencil, what this for loop does, you will see that it iterates for values of x 0 through 9, that's what this says. x starts with 0. When it reaches 10, x < size will be false and the loop ends, so the loop runs with x ranging from 0 to 9.
if(minimum > array[x+1]){
Since x will range from 0-9, it logically follows that x+1 will range from 1 to 10, and so this if statement will check the values in array[1] through array[10].
In C++ array indexes start with 0, not 1. The values in your array are array[0] through array[9]. array[10] does not exist, so the above code is undefined behavior.
Furthermore:
int array[size];
This is not valid C++ either. Your C++ compiler may allow this as a non-standard C++ extension, but array sizes must be fixed, constant sizes in C++, determined at compile time. You can't use a non-constant variable to set the size of an array, C++ does not work this way. If you need to have an array of size that's determined at runtime then you need to use std::vector instead of a plain array, and change the rest of your code accordingly.
Mistake 1
Your example has undefined behavior because of the expression array[x+1]. That is, for the last iteration of the for loop, you're going out of bounds of the array and so have undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
In standard C++, the size of an array must be a compile time constant. So in your code:
int size;
cin >> size;
int array[size]; //NOT STANDARD C++
The statement int array[size]; is not standard C++ because size is not a constant expression.
Additionally you don't need 2 separate for loops when you can achieve the goal in 1 for loop as shown below.
Solution 1
You can use std::vector as shown below:
#include <iostream>
#include <vector>
#include <climits>
//this function take a vector as input
void value(const std::vector<int>& arr)
{
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the vector to find the max and min value
for(const int& element: arr)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num; //return the difference of mx and min value
}
int main()
{
int n;
std::cout<<"elements: ";
std::cin >> n;
//create vector of int of size n
std::vector<int> arr(n);
//take elements from user
for(int i=0; i<n; i++)
{
std::cin >> arr[i];
}
value(arr);
return 0;
}
Demo
Solution 2
You can make the function a function template so that you don't need to pass a separate argument to the function as shown below:
#include <iostream>
#include <climits>
//N is a nontype template parameter
template<std::size_t N>
void value(const int (&array)[N]){
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the array to find the max and min value
for(const int& element: array)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num;
}
int main(){
int array[3] = {};
for(int x = 0; x < sizeof (array) / (sizeof (array[0])); x++){
std::cout << "Input #" << x+1 <<": ";
std::cin >> array[x];
}
value(array); //no need to pass the second argument
return 0;
}
Demo
Also note that with C++17, you can use std::size instead of sizeof (array) / (sizeof (array[0])) to find the length of the array.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

How do I find highest value using pointer?

I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a[10], i, index;
int *p, *max;
for (i = 0; i < 10; i++) cin >> a[i];
max = 0;
p = &a[10];
for (index = 0; index < 10; index++) {
if ((p[index]) > *max) {
*max = (p[index]);
}
}
cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
return 0;
}
The code is buggy. First of all, you assign
p=&a[10];
This assigns p to a memory address past a. Furthermore, you then index as p[index], which essentially is the same as a[10 + index].
Also, max is a wild pointer. It does not point to anything. You are assigning values to an undefined memory location.
I would strongly suggest to read up on pointers and to properly understand them before using them. Also, in modern C++, it is not very often than you need pointers.
Also, in idiomatic C++, we would probably write
auto p = std::max_element(a, a + 10);
There are several problems.
First, p should point to the array's first element, so you should have p = &a[0].
You can also rely on implicit conversion and just write p = a;, which is exactly the same.
&a[10] is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.
Next, you want max to point to the maximum element.
It should also start at the beginning of the array, like p.
Then, when you find a new maximum, you should make max point to that element, not change the value max points to.
Lastly, index will always be 10 after the search loop.
(Take a few moments to think about why.)
You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.
int main()
{
int a[10];
for(int i = 0; i < 10; i++)
cin >> a[i];
int* max = &a[0];
int* p = &a[0];
for (int index = 0; index < 10; index++){
if (p[index] > *max){
max = &p[index];
}
}
cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}
I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.
Comments in the code:
#include <iostream>
#include <iterator>
// using namespace std; // don't do this
int main() {
using std::cin, std::cout;
int a[10];
// use a range-based for-loop:
for(int& aref : a) { // aref is a reference to the current element in a
// check that extraction from std::cin actually works
if(!(cin >> aref)) {
std::cerr << "error reading int\n";
return 1;
}
}
// initialize max to point at the first element
auto max = std::begin(a);
// Start at the second element since max is already set to point at the first element.
// Don't use magic numbers. Define a constant or use std::size(<array>)
// ...or use iterators like in this example:
for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
if(*curr > *max) {
max = curr;
}
}
// you can use std::distance ot calculate the index for max:
cout << "Highest value=" << *max << '\n'
<< "is at index=" << std::distance(std::begin(a), max) << '\n';
}
The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.
I tried to make the least amount of changes to the original code:
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *p,*max;
for(i=0;i<10;i++)
cin>>a[i];
max=a; // Initialize max to point to the first item in a
p=a;
for(index=0;index<10;index++){
if((p[index])>*max){
max=(&p[index]); // Now make max point to the new maximum item
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
return 0;
}
Here is the code in ideone:
https://ideone.com/BwE45C
As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *max;
for(i=0;i<10;i++)
cin>>a[i];
max=a;
for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
if(*p>*max){
max=p; // max points to the new maximum
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
return 0;
}
The new ideone link for this is here: https://ideone.com/bk3zoS

My program keeps throwing compilation error,I am not able to figure out why the error has occured

Can't seem to figure out the error that the program keeps throwing.The program keeps throwing the error when I am dereferencing an iterator.Could anyone tell me where did I go wrong?
The problem for the code goes like this "Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers."
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
int sum = 0;
unordered_map<int,int> results;
for(size_t i = 0;i < arr.size();i++)
{
results[arr[i]] = accumulate(arr.begin(),arr.end(),sum) - arr[i];
}
pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator> mn;
mn = minmax_element(results.begin(),results.end());
cout<< *mn.first<<" "<<*mn.second; //line where the error is occuring
}
Solution.cpp: In function 'void miniMaxSum(std::vector)':
Solution.cpp:9:9: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'std::pair')
cout<< *mn.first<<" "<<*mn.second;
~~~~^~~~~~~~~~~~
Edit: my answer fixes the compilation problem, but OP function does not do what they wanted it to do. John's answer solves the real algorithmic problem.
I reworked your snippet to make it immediately compilable:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <unordered_map>
using namespace std;
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
int sum = 0;
unordered_map<int,int> results;
for(size_t i = 0;i < arr.size();i++)
{
results[arr[i]] = accumulate(arr.begin(),arr.end(),sum) - arr[i];
}
pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator> mn;
mn = minmax_element(results.begin(),results.end());
auto minIt = mn.first;
auto maxIt = mn.second;
cout<< "key min elem: " << minIt->first << " value min elem: " << minIt->second;
cout<< "key max elem: " << maxIt->first << " value max elem: " << maxIt->second;
}
The issue is the type of mn: pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator>. mn is a pair. With mn.first you get an iterator to a key-value pair (the pair the error refer to). Once you have your pair you need to access directly the element you are interested in. I made the passage explicit in my example. You can look here (example at the bottom): https://en.cppreference.com/w/cpp/container/unordered_map for the structure of iterators on a unordered_map .
PS: you might want to avoid using namespace std I did it to keep the differences between your and my snippet to the minimum.
So here's the way to solve your problem
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
vector<int> results(arr.size());
for (size_t i = 0; i < arr.size();i++)
{
results[i] = accumulate(arr.begin(), arr.end(), 0) - arr[i];
}
auto mn = minmax_element(results.begin(), results.end());
cout << *(mn.first) << " " << *(mn.second);
}
The basic error was that you picked unordered_map<int,int> instead of vector<int> to store your intermediate results.
And notice that the correct syntax is *(mn.first) and *(mn.second) because you have a pair of iterators not an iterator pointing at a pair.
Working example

How do you print a full array of values in C++

I'm trying to figure out print a full array in C++.
For example, I want the output to be x = [1,2,3,4,5....n]
How would I go about doing this? I already know how to print each element of the array using a simple for loop. For example in python, you could simply say x = [], make a for loop to append elements to the array, and print x.
So let's say I have this code.
int n = 10;
int m = 10;
double x[n];
// Generate vector of random values for x
for (int i = 0; i<n; ++i)
{
x[i] = (double)rand()/(double)RAND_MAX;
// Print each array element
// std::cout << x[i] << std::endl;
}
std::cout << x[n-1] << std::endl;
This obviously only spits out x[10] in this case. Where as I want x = [1...n] etc.
What is the simplest way of achieving this?
I'm using Eclipse on OSX. I use the g++ compiler that the Xcode developer tools has for the command line
You're looking for a range based for loop:
double x[] = { .0, .1, .2, .3, .4 };
// Iterate through all elements
for (auto d : x)
{
std::cout << d << std::endl;
}
Note that the above takes a copy of each element, so if you wanted to modify an element you'd need to use
for (auto& d : x)
instead.
Alternatively you could just use a normal for loop like you did originally:
for (int i = 0; i<n; ++i)
{
std::cout << x[i] << std::endl;
}
The range based for loop is the easiest though.
if you know something about STL , you can try to use iterator
code:
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int arr[5] = {1,2,3,4,5};
copy(arr, arr + sizeof(arr)/sizeof(int),ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}

C++ Program Apparently Printing Memory Address instead of Array

#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;
}
The purpose of this program is for the user to input a space-separated series of values ended by a 0. That array is then to be analyzed to find the max. I figured out how to convert what is originally a char[] into an int[] so that I can use the findMax() function on it without error but the sorting loop seems to have a problem of its own and when "cout << values << endl << mval;" is called, it returns only a memory address instead of what should be a non-spaced sequence of ints. Can anybody explain what I am doing wrong? It seems that I may have made some mistake using the pointers but I cannot figure out what.
Printing values won't print the contents of the array as you expect, it will print the memory location of the first element of the array.
Try something like this instead:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Sorry I can't post actual working code, but your original post is a mess with many syntax and syntactic errors.
EDIT: In the interest of being more complete and more approachable & understandable to beginners, I've written a small program that illustrates 4 ways to accomplish this.
Method 1 uses copy with an ostream_iterator as I've done above.
Method 2 below is probably the most basic & easiest to understand.
Method 3 is a C++0x method. I know the question is tagged C++, but I thought it might be educational to add this.
Method 4 is a C++ approach using a vector and for_each. I've implemented a functor that does the dumping.
Share & Enjoy
#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;
}
When you pass around an array of X it's really a pointer to an array of X that you're passing around. So when you pass values to cout it only has the pointer to print out.
You really should look into using some of the standard algorithms to make your life simpler.
For example to print all the elements in an array you can just write
std::copy(values, values+MAX, std::ostream_iterator<int>(std::cout, "\n"));
To find the max element you could just write
int mval = *std::max_element(values, values+MAX);
So your code becomes
#include <iostream>
using namespace std;
int main(){
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);
}
copy(values, values+MAX, ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values, values+MAX);
return 0;
}
Doing this removes the need for your findMax method altogether.
I'd also re-write your code so that you use a vector instead of an array. This makes your code even shorter. And you can use stringstream to convert strings to numbers.
Something like this should work and is a lot less code than the original.
int main(){
vector<int> values;
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
int temp = 0;
stringstream ss(ivals);
//read the next int out of the stream and put it in temp
while(ss >> temp) {
//add temp to the vector of ints
values.push_back(temp);
}
copy(values.begin(), values.end(), ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values.begin(), values.end());
return 0;
}
Array of int is promoted to a pointer to int when passed to a function. There is no operator << taking ordinary array. If you want to use operator << this way, you need to use std::vector instead.
Note: it is possible technically to distinguish array when passed to a function using template, but this is not implemented for standard operator <<.
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
sizeof(arr) here is the size of the pointer to the array. C++ will not pass the actual array, that would be grossly inefficient. You'd typically only get one pass through the loop. Declare your function like this:
int findMax(int* arr, size_t elements) {
//...
}
But, really, use a vector.
Oh, hang on, the question. Loop through the array and print each individual element.