C++ 将数组指针作为函数参数传递 [英] C++ passing an array pointer as a function argument

查看:52
本文介绍了C++ 将数组指针作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数组指针作为生成数组的函数的参数.

I'm trying to use pointers of arrays to use as arguments for a function which generates an array.

void generateArray(int *a[],  int *si){
  srand(time(0));
  for (int j=0;j<*si;j++)
       *a[j]=(0+rand()%9);
} //end generateArray;

int main() {
  const int size=5;
  int a[size];

  generateArray(&a, &size);

  return 0;
} //end main

但是当我编译这个消息时出现:

But when I compile this this message appears:

cannot convert `int (*)[5]' to `int**' for argument `1' to `void generateArray(int**, int*)'

推荐答案

你把它复杂化了——它只需要:

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
{
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;
}

int main()
{
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;
}

当您将数组作为参数传递给函数时,它会衰减为指向数组第一个元素的指针.所以通常不需要将指针传递给数组.

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

这篇关于C++ 将数组指针作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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