mercredi 8 avril 2020

SegFault in Reversing Line of 2D Array

I'm trying to reverse the lines of a 2D array of doubles. Since the array is dynamic, it's created like

double** revArr = new double*[m];
for (int i = 0; i < m; i++)
    revArr[i] = new double[n];

I end up copying the original array to the reversed array by normal fashion

for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
        revArr[i][j] = arr[i][j];

Now here comes the kicker! Then I try to reverse the line of the array, and have tried a few different ways.

int start = 0, end = n;
for (int i = 0; i < m; i++) {
    while (start < end)
    {
        double *temp = revArr[start];
        revArr[start] = revArr[end];
        revArr[end] = temp;
        start++; end--;
    }
}

Which since the array is an array of double*, it throws a SegFault that I'm not really sure how to fix!

I've tried using std::swap, I've tried using std::reverse, I'm not really sure where to turn to from here.

Minimum reproducible example:

#include <iostream>

int main() {
    int m = 4, n = 4;

    double* arr = new double[m];
    for (int i = 0; i < m; i++)
        arr[i] = new double[n];

    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            arr[i][j] = i + j;

    int start = 0; end = n;
    for (int i = 0; i < m; i++) {
        while (start < end)
        {
            double *temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++; end--;
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire