molten
molten

Reputation: 53

Dynamic array in main and in function

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?

Upvotes: 0

Views: 62

Answers (2)

juanchopanza
juanchopanza

Reputation: 227438

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);
}

Upvotes: 2

deeiip
deeiip

Reputation: 3379

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();

}

Upvotes: 0

Related Questions