dimanche 26 juin 2016

crash connected to passing std::array


This question has been completely re-written. Please, consider going through the whole text once more.


I'm having problems with a program that makes use of standard arrays. The code below is the full program as stripped as possible and still reproducing the error.

I couldn't understand where the problem may be. As you may read, the comments 1, 2(both at the same time) and 3 all signal pieces of code that, if removed, cause the program to run without crashes.

Furthermore, setting the costant N to 3 or using other combinations of values for the arrays all cause the program to run to completion. Please, note that division by 0 can't explain all of the failure points (see comment #3).

#include <iostream>
#include <array>
#include <math.h>

#define N 4

void f1(std::array<std::array<float, N>, N> a, std::array<float, N> b, std::array<float, N>& c);
void f2a(std::array<std::array<float, N>, N>& a, std::array<float, N>& b, std::array<float, N>& d);
void f2b(std::array<std::array<float, N>, N>& a, std::array<float, N>& b, std::array<float, N>& d, int i);
void f3(std::array<std::array<float, N>, N> a, std::array<float, N> b, std::array<float, N>& c);

int main()
{
    std::array<std::array<float, N>, N> a = { { { 1, 1, 0, 3 },{ 2, 1, -1, 1 },{ 3, -1, -1, 2 },{ -1, 2, 3, -1 } } };
    std::array<float, N> b = { 4, 1, -3, 4 };
    std::array<float, N> c;

    f1(a, b, c);

    std::cin.get();

    return 0;
}

void f1(std::array<std::array<float, N>, N> a, std::array<float, N> b, std::array<float, N>& c)
{
    std::array<float, N> d;

    for (int i = 0; i < N; i++)
    {
        d[i] = fabs(a[i][0]);

        for (int j = 1; j < N; j++)
        {
            if (fabs(a[i][j] > d[i]))
            {
                d[i] = fabs(a[i][j]);
            }
        }
    }

    //switching b and d
    f2a(a, b, d);

    f3(a, b, c);

}

void f2a(std::array<std::array<float, N>, N>& a, std::array<float, N>& b, std::array<float, N>& d)
{
    for (int i = 0; i < (N - 1); i++)
    {
        f2b(a, b, d, i);
    }
}

void f2b(std::array<std::array<float, N>, N>& a, std::array<float, N>& b, std::array<float, N>& d, int i)
{
    float float1, float2;
    int p = i;

    float1 = fabs(a[i][i] / d[i]);

    for (int ii = (i + 1); ii < N; ii++)
    {
        float2 = fabs(a[ii][i] / d[ii]);

        if (float2 > float1)
        {
            float1 = float2;
            //11
            p = ii;
        }
    }

    if (p != i)
    {
        //2
        THE MISTAKE IS HERE, WHERE i IS WRITTEN FOR ii
        for (int ii = i; i < N; i++)
        {
            float2 = a[p][ii];
            a[p][ii] = a[i][ii];
            a[i][ii] = float2;
        }

        //2
        float2 = b[p];
        b[p] = b[i];
        b[i] = dummy;
    }

}

void f3(std::array<std::array<float, N>, N> a, std::array<float, N> b, std::array<float, N>& c)
{
    //3
    c[0] = 0;
}

Aucun commentaire:

Enregistrer un commentaire