如何使双指针参数的C函数自动? [英] How to make a double pointer argument automatic in a C function?

查看:168
本文介绍了如何使双指针参数的C函数自动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为make5简单的函数,使得等于5一个二维矩阵的每个元素,如下图所示:

I have a simple function called make5 that makes every element in a 2d matrix equal to 5, shown below:

int make5(int r, int c, double **d)
{
  int i, j;

  for (i = 0; i < r; i++) {
    for (j = 0; j < c; j++) {
      d[i][j] = 5;
    }
  }

  return 0;
}

我希望能够运行在不同的矩阵此功能,请使用以下电话:

I'd like to be able to run this function on different matrices, using the following calls:

make5(2, 3, a);
make5(2, 4, b);

其中A和B都被宣布为指针,数组的数组。但是,当我尝试这个我不断收到分段错误。我怎样才能改变make5这样我就可以在A和B运行呢?

where a and b have been declared as pointers to arrays of arrays. But when I try this I keep getting a segmentation fault error. How can I change make5 so I can run it on both a and b?

推荐答案

函数工作得很好。你必须正确地分配内存或传递错误的参数给函数。

The function works just fine. You must be allocating the memory incorrectly or passing wrong parameters to the function.

的例子:

#include <stdio.h>
#include <stdlib.h>

int make5(int r, int c, double **d)
{
  int i, j;

  for (i = 0; i < r; i++) {
    for (j = 0; j < c; j++) {
      d[i][j] = 5;
    }
  }

  return 0;
}

#define ROWS 4
#define COLS 3

int main(void)
{
  double** p = malloc(ROWS * sizeof(double*));
  int i, j;

  for (i = 0; i < ROWS; i++)
    p[i] = malloc(COLS * sizeof(double));

  for (i = 0; i < ROWS; i++)
    for (j = 0; j < COLS; j++)
      p[i][j] = 1;

  for (i = 0; i < ROWS; i++)
  {
    for (j = 0; j < COLS; j++)
      printf("%f ", p[i][j]);
    printf("\n");
  }

  make5(ROWS, COLS, p);

  for (i = 0; i < ROWS; i++)
  {
    for (j = 0; j < COLS; j++)
      printf("%f ", p[i][j]);
    printf("\n");
  }

  return 0;
}

输出( ideone ):

1.000000 1.000000 1.000000 
1.000000 1.000000 1.000000 
1.000000 1.000000 1.000000 
1.000000 1.000000 1.000000 
5.000000 5.000000 5.000000 
5.000000 5.000000 5.000000 
5.000000 5.000000 5.000000 
5.000000 5.000000 5.000000 

这篇关于如何使双指针参数的C函数自动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆