Doug Ray
Doug Ray

Reputation: 1010

C++ passing array by value causing segment fault

Hey everyone I am relearning C++ by doing some hacker rank challenges and am getting a segment fault error. The program should take in the dimensions for the matrix and compute both diagonals, then add them together. I am pretty sure the error is in how the 2d array is passed to the computeMainDiagonal and computeSecondaryDiagonal functions. Thanks for the help !

int ComputeMatrixMainDiagonal(int matrixDimensions, int* matrix){
    int rowIndent = 0;
    int diagonalValue; 

    for(int i = 0;i < matrixDimensions;i++){
        diagonalValue =+ (&matrix)[i][rowIndent];
        rowIndent++;
    }
    return diagonalValue;
}

int ComputeMatrixSecondaryDiagonal(int matrixDimensions, int* matrix){
    int rowIndent = matrixDimensions;
    int diagonalValue;

    for(int i = matrixDimensions;i > 0;i--){
        diagonalValue =+ (&matrix)[i][rowIndent];
        rowIndent--;
    }
    return diagonalValue;
}


int main() {
    int matrixDimension;
    int differenceAcrossSumsOfDiagonal;
    int matrixMainDiagonal;
    int matrixSecondaryDiagonal;

    int * matrixPointer;

    cin >> matrixDimension; //get matrix dimensions
    int matrix[matrixDimension][matrixDimension]; //declare new matrix
    for(int index = 0; index < matrixDimension;index++ ){ //populate matrix
        for(int i = 0; i < matrixDimension;i++){
            cin >> matrix[index][i];
        }
    }
    matrixMainDiagonal = ComputeMatrixMainDiagonal(matrixDimension,&matrix[matrixDimension][matrixDimension]);      
    matrixSecondaryDiagonal = ComputeMatrixSecondaryDiagonal(matrixDimension,&matrix[matrixDimension][matrixDimension]);

    differenceAcrossSumsOfDiagonal = (matrixMainDiagonal + matrixSecondaryDiagonal);

    cout << differenceAcrossSumsOfDiagonal;

    return 0;
}

Upvotes: 0

Views: 372

Answers (1)

John Bollinger
John Bollinger

Reputation: 181814

Your segmentation fault likely occurs because &matrix[matrixDimension][matrixDimension] does not mean what you think it means. Your question title suggests that you think this is a way to pass the array by value (though why you would want to do so escapes me), but pass-by-value vs. pass-by-reference is a matter of how the function is declared, not of how it is called.

The expression &matrix[matrixDimension][matrixDimension] would be the address of the matrixDimensionth element of the matrixDimensionth row of the matrix. This is outside the bounds of the matrix, as the maximum index for an array is one less than the array dimension. Even if you wrote &matrix[matrixDimension - 1][matrixDimension - 1], however, it would not be what you want. You want the address of the first element of the array, which is &matrix[0][0] or simply matrix, though these are inequivalent on account of having different type (corresponding to different senses of what the elements of matrix are).

Upvotes: 1

Related Questions