Ron Axm
Ron Axm

Reputation: 101

How to fix unhandled exception access violation

I have written a logic to find out common elements from two arrays. But the program breaks at the if condition giving an exception saying Access violation reading location 0x00000002.

#include<stdio.h>
void intersect(int[2][2],int[2][2],int,int);
int main()
{
    int arr1[2][2]={{2,5},{6,8}};
    int arr2[2][2]={{1,2},{8,8}};
row = (sizeof(arr1)/sizeof(arr1[0]));
     col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
intersect(arr1,arr2,row,col);
}

void intersect(int **ptr1, int **ptr2,int row, int col)
{
    int i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
                for(x = 0; x < row ; x++)
                {
                    for(y = 0; y < col ; y++)
                    {
                        if(ptr1[i][j] == ptr2[x][y]) 
                            printf("%d\t",ptr1[i][j]);

                    }
                }
        }
    }
}

This is what it says in detail: First-chance exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002. Unhandled exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002.

Upvotes: 2

Views: 572

Answers (3)

Martymoose
Martymoose

Reputation: 78

This works... not sure if it's what you wanted.

void intersect(int** ptr1, int** ptr2, size_t row, size_t col)
{
int i = 0, j = 0, x = 0, y = 0;

for (i = 0; i < row; i++)
{
    for (j = 0; j < col; j++)
    {
        for (x = 0; x < row; x++)
        {
            for (y = 0; y < col; y++)
            {
                int a = *(int*)((DWORD)ptr1 + (i * (col * sizeof(int))) + (j * sizeof(int)));
                int b = *(int*)((DWORD)ptr2 + (x * (col * sizeof(int))) + (y * sizeof(int)));

                if (a == b)
                    printf("%d\t", a);
            }
         }
      }
    } 
 }

Upvotes: 0

Achal
Achal

Reputation: 11921

when you are passing 2D array as a argument to function, you should catch with pointer to an array not with double pointer because 2D array and double pointer are not same..

    #define r 2
    #define c 2


    void intersect(int (*ptr1)[r], int (*ptr2)[c],int row, int col)
    {
           //function body
    }

Upvotes: 0

4386427
4386427

Reputation: 44274

Instead of using ptrN as double pointers, you can tell the array size like:

void intersect(size_t row, size_t col, int a1[][col], int a2[][col])
{
    size_t i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
            for(x = 0; x < row ; x++)
            {
                for(y = 0; y < col ; y++)
                {
                    if(a1[i][j] == a2[x][y]) 
                        printf("%d\t",a1[i][j]);
                }
            }
        }
    }
}

Upvotes: 1

Related Questions