Rdd
Rdd

Reputation: 23

Modifying the values of a 2d array of reference in a function

This program must have a function that can accept 2 arrays and return their product in a third array. All of the arrays must be 2d, and a separate function must complete the multiplication of the elements memberwise. When I run this in visual studio I get the error:

Unhandled exception at 0x003f15ec in program4.exe: 0xC0000005:  
Access violation reading location 0x00000000.

This could be due to my lack of knowledge about C++, but I think I may have made a syntax mistake or something. Here is the program:

#include<iostream>
using namespace std;

void ProductArrays(int[3][4], int[3][4], int** array3[3][4]);


void main()
{
int array1[3][4] = { {1,3,5,7}, {9,11,13,15},  {17,19,21,23} };
int array2[3][4] = { {2,4,6,8}, {10,12,14,16}, {18,20,22,24} };
int** array3[3][4] = {0,0,0,0,0,0,0,0,0,0,0,0};

ProductArrays(array1, array2, array3);

system("pause");
return;
}

void ProductArrays(int array1[3][4], int array2[3][4], int** array3[3][4])
{
int i,j;
for (i=0;i<3;i++)
    {
    for(j=0;j<4;j++)
        {
          **array3[i][j] = array1[i][j] * array2[i][j];
        }
    }
return;
}

Upvotes: 2

Views: 166

Answers (2)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

(1)
The declaration for array3 is wrong as you required.

int** array3[3][4] = {0,0,0,0,0,0,0,0,0,0,0,0};

You need this If I correctly understand you question:

int array3[3][4] = {0,0,0,0,0,0,0,0,0,0,0,0};

(3)
You are getting error because you were creating 2D array of pointers those are pointing to NULL (0) and you are assigning to 0 location.

**array3[i][j] = array1[i][j] * array2[i][j];
               ^ assign to `0` location 

(2)
Declare you function like:

void ProductArrays(int array1[3][4], int array2[3][4], int (*array3)[4])
{ //                                                          ^ notice
int i,j;
for (i=0;i<3;i++)
    {
    for(j=0;j<4;j++)
        {
           array3[i][j] = array1[i][j] * array2[i][j];
        // ^ remove **  
        }
    }
return;
}

call it from main like:

ProductArrays(array1, array2, array3);

Additional point, my answer is pass by address, and @Barry's answer is pass by reference. In C++ Both are allowed. (in C only pass by address is possible)

Pass by reference having power of pointers but simple to use like value variables So @Barry's answer is better. consider my answer for understanding points of view.

Upvotes: 1

Barry
Barry

Reputation: 303097

I think what you mean for array3 to be a reference to a 2d array of pointers, but it's actually a 2d array of int**. So when you do the multiplication, this part:

**array3[i][j]

Is trying to dereference what's in array3[i][j], which is 0, hence the AccessViolation. I think you probably mean the signature to be:

void ProductArrays(int array1[3][4], int array2[3][4], int (&array3)[3][4])

And declare array3 to be of the same type as array1 and array2.

Upvotes: 2

Related Questions