三指针作为参数 - 矩阵乘法

时间:2015-02-15 03:23:41

标签: c dynamic matrix

我正在研究Matrix Multiplication问题,我正在动态分配数组

以下是我目前的情况:

全局:

int **a;

在我的allocatematrix函数中:(m - row,k - col)

    a = (int **)malloc(m * sizeof(int *));
    for (i=0; i<m; i++)
    {
         a[i] = (int *)malloc(k * sizeof(int));
    }

    // Note that arr[i][j] is same as *(*(arr+i)+j)
    // just to test my array allocation is working
    for (i = 0; i < m; i++)
    {
      for (j = 0; j < k; j++)
      {
         a[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
      }
    }


    for (i = 0; i <  m; i++)
    {
      for (j = 0; j < k; j++)
      {
         printf("%d ", a[i][j]);
      }
      printf("\n");
    }

    // I would like to pass my pointer to pointer
    // into a subroutine, such that it transforms the 
    // the global double array, but it keeps blowing up here
    loadMatrix(fp, &a, m, k);

加载矩阵函数:

// read in the file
void loadMatrix(FILE *fp, int ***arr, int size1, int size2)
{
    //fp = fopen(name, "r");
    if (fp == NULL)
    {
        printf("Error while opening file!\n");
        exit(0);
    }

    int i, j;
    for(i = 0; i < size1; i++)
    {
        for(j = 0; j < size2; j++)
        {
            int value = 0;
            fscanf(fp, "%d", &value);
            printf("Current Value: %d\n", value);
            //value =  (((arr + i)) + j);
            // line below is where I think I have the issue 
            *(*(*(arr+i)+j)) = value;
        }
    }
}

示例运行:使用此行注释(*(arr + i)+ j))= value;

3 2 3 
1 2 
3 4 
5 6 
Current Value: 1
Current Value: 4
Current Value: 2
Current Value: 5
Current Value: 3
Current Value: 6

没有注释掉:

3 2 3 
1 2 
3 4 
5 6 
Current Value: 1
Current Value: 4
Current Value: 2
Segmentation fault (core dumped)

1 个答案:

答案 0 :(得分:0)

你不需要一个int ***指针,如果你传递一个指针,它指向的数据将被该函数修改,你能做的就是这个

// read in the file
void loadMatrix(FILE *fp, int **arr, int size1, int size2)
{
    if (arr == NULL)
        return;
    if (fp == NULL)
    {
        printf("Error while opening file!\n");
        exit(0);
    }

    int i, j;
    for (i = 0 ; i < size1 ; i++)
    {
        for (j = 0 ; j < size2 ; j++)
        {
            int value = 0;
            /* test that fscanf() succeeded reading an integer */
            if (fscanf(fp, "%d", &arr[i][j]) != 1)
                arr[i][j] = 0; /* this just prevents that arr[i][j] be uninitialized */
        }
    }
}

如果你说你测试你的分配是有效的,那不会测试任何东西,唯一可以执行的测试是来自malloc()的返回值,如果分配失败则返回NULL,所以测试你的分配工作是这样完成的

a = malloc(m * sizeof(int *));
if (a == NULL)
    pleaseDoSomethingAboutIt_AllocationFailed_DoNotContinue();
for (i = 0 ; i < m ; i++)
{
     a[i] = malloc(k * sizeof(int));
     if (a[i] == NULL)
     {
         while (--i)
             free(a[i]);
         free(a);
         pleaseDoSomethingAboutIt_AllocationFailed_DoNotContinue();
     }
}

如果分配失败,并且您仍然取消引用指针,就像在测试中一样,您将调用未定义的行为,因此您无法测试任何内容,因为您无法知道将会发生什么。