0

If I run this code like this it gives segmentation fault error. However if I put the for loop in main it works fine. I don't get it why it happens?

0

2 Answers 2

2

Your deneme function is iterating over a pointer that is not initialized to point to an array. This is because in main you initialize a different pointer of the same name.

Besides that, you have undefined behaviour here:

lol_array[i].point += (ant_count-i); 

because point is not initialized. You could force your array elements to be value initialized, and hence their data members to be zero initialized, like this:

// value-initialize array and assign to global pointer
lol_array = new forsort[ant_count]();
//                                ^^ 

Note, in real life you would probably use an std::vector<forsort> or an std::unique_ptr<forsort[]>. For example,

void deneme(std::vector<forsort>& v)
{

  for (auto count = v.size(), i = 0; i < count; ++i)
    fs[i].point += (count-i); 
}

int main()
{
  std::vector<forsort> v(ant_count);
  deneme(v);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You may use the following code (although it is not very safe):

struct forsort
{
    int point;
    int id;
};


forsort* lol_array;

void deneme(int ant_count)
{
    for (int i = 0; i < ant_count; i++)
        {
            lol_array[i].point += (ant_count-i); 
        }
}

int main ()
{

    int ant_count =4;
     lol_array = new forsort[ant_count]; 
     //here you need to initialise the contents properly as juanchopanza suggested
    deneme(ant_count);
    getch();

}

1 Comment

Still undefined behaviour (see 2nd part of my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.