I am trying to use the new C++11 range based for loops. Here’s my program:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
ofstream logger("log.txt");
void log(string message)
{
logger << message << std::endl;
logger.flush();
}
int main( int argc, char* args[] )
{
log("hello world");
cout << "hello world\n";
log("declare sort me");
int sortMe[10];
log("loop sortMe");
for(int i : sortMe) {
log("in loop " + i);
sortMe[i] = i + 1;
}
}
I’m using clang++ to compile. It compiles with the warning:
clang++ -o mycpp mycpp.cpp
mycpp.cpp:24:12: warning: range-based for loop is a C++11 extension
[-Wc++11-extensions]
for(int i : sortMe) {
^
1 warning generated.
When it runs, I get this output:
hello world
Segmentation fault (core dumped)
According to the log.txt file, the program gets to the for loop, but it never enters the for loop. What am I missing?
This loop:
Loops and returns the values stored in the
sortMearray, not the indices of thesortMearray. As a result, the lookupsortMe[i]will jump to a totally random index of the array (probably way, way out of bounds), causing the segfault.If you want to set each element equal to its position, just use a normal for loop:
Also, as @hmjd noted, the call to
logwill not work correctly, because you are doing pointer arithmetic on a string, not doing a string concatenation.Hope this helps!