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?
Asked
Active
Viewed 62 times
2 Answers
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);
}

juanchopanza
- 223,364
- 34
- 402
- 480
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();
}

deeiip
- 3,319
- 2
- 22
- 33
-
Still undefined behaviour (see 2nd part of my answer). – juanchopanza Nov 17 '13 at 13:04