Search code examples
c++for-loopcoredump

float for loop, core dumped c++


I don't understand what I'm doing wrong. My code should just increment i: 0.1 from zero, and add 0.5 to each position, really simple, but instead I get segmentation fault (core dumped).

Can someone give me hand?

vector<float> sinal;

int main(){
  sinal[0] = 0;
  for (float i = 0.1; i <= 1; i += 0.1){
    sinal[i] = sinal[i - 1] + 0.5;
    if (i == 1){
      break;
    }
    cout << "\n" << sinal[i];
  }

getchar();
cin.get();
}
 

Solution

  • Two problems here:

    1. When you access sinal[0] and sinal[i], sinal does not have any capacity yet.

    2. Using a floating point number as a subscript is unusual, and could make errors happen. The subscript is normally the offset of the item you want to access, so if I want to access the fifth element, I use a subscript of 4, because I move forward 4 spaces to get to the fifth element. If I do 1.5 as a subscript, then I am trying to move forward 1 and 1/2 spaces, and our std::vector does not understand that. I am guessing that the overload of operator[] for vector takes only an int, so some kind of cast happens when you put a float.

    For a solution, take a look at my other answer here: Not getting output in case of string.

    "Core Dumped" is often trying to dereference a null pointer, or, in this case, trying to access an out of range object.