如何修复未处理的异常访问冲突

时间:2017-11-13 16:43:32

标签: c pointers

我写了一个逻辑来找出两个数组中的常见元素。但是该程序在if条件下中断,给出了一个异常,称访问冲突读取位置为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]);

                    }
                }
        }
    }
}

这是它详细说的:Array.exe中0x002b1572的第一次机会异常:0xC0000005:访问冲突读取位置0x00000002。 Array.exe中0x002b1572处的未处理异常:0xC0000005:访问冲突读取位置0x00000002。

3 个答案:

答案 0 :(得分:1)

您可以将数组大小告诉:

,而不是使用ptrN作为双指针
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]);
                }
            }
        }
    }
}

答案 1 :(得分:0)

当您将2D array作为参数传递给函数时,您应该使用pointer to an array而不是双指针,因为2D数组和双指针不相同..

    #define r 2
    #define c 2


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

答案 2 :(得分:0)

这有效......不确定这是不是你想要的。

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);
            }
         }
      }
    } 
 }