C 指针表示法与数组表示法的比较:传递给函数时 [英] C pointer notation compared to array notation: When passing to function

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

问题描述

我的问题基于以下代码:

My question is base on the following code:

int myfunct(int ary[], int arysize)   
int myfunct2(int *ary, int arysize)

 int main(void){
   int numary[10];
   myfunct(numary, 10)
   myfunct2(numary, 10)
   return;
 }

int myfunct(int ary[], int arysize) {   
      //Whatever work is done

  }

int myfunct2(int *ary, int arysize) {
     // Whatever work is done

  }

是否有理由使用其中一个而不是另一个?详细说明,当涉及数字数组时,是否有任何理由希望使用指针表示法而不是数组表示法.如果使用指针表示法,则在函数中将使用指针算术等.如果使用 [] 数组表示法,则可以像往常一样使用数组.我是编程新手,目前我认为使用指针表示法没有任何好处.

Is there a reason to use one of these over the other? To elaborate, when concerned with numeric arrays, is there any reason one would want to use pointer notation over array notation. If one uses pointer notation then within the function pointer arithmetic would be used etc.. AND if one uses the [] array notation, one could work with the array as usual. I'm new to programming and I currently do not see any benefit to using the pointer notation.

我的确切问题是,是否有任何理由使用指针表示法将数字数组传递给函数,从而在函数内使用指针操作.

My precise question, is there any reason to pass a numeric array to a function using pointer notation and therefore using pointer manipulations within the function.

推荐答案

这两种表示法在功能上没有真正的区别.在 C 中,当您将数组变量传递给函数时,无论表示法如何,它都会衰减为指针.但是,在我看来,指针表示法更可取.函数定义中 [] 符号的问题在于,在我看来,它有点误导:

There is no real functional difference between the two notations. In C, when you pass an array variable to a function, it decays to a pointer regardless of the notation. However, in my opinion, the pointer notation is preferable. The problem with [] notation in function definitions is that, in my opinion, it is somewhat misleading:

void foo(int array[])
{

}

C 新手程序员普遍存在的错误是假设 sizeof(array) 会给你数组中的 元素数量 乘以 sizeof(int),就像 array 是在堆栈上声明的数组变量一样.但实际情况是 array 已经退化为一个指针,尽管有误导性的 [] 符号,所以 sizeof(array) 将是 sizeof(int*).array 实际上只是一个指向第一个元素的指针,或者可能是一个指向分配在任何地方的单个整数的指针.

A ubiquitous mistake among novice C programmers is to assume that sizeof(array) will give you the number of elements in the array multiplied by sizeof(int), like it would if array were an array variable declared on the stack. But the reality is that array has been decayed to a pointer, despite the misleading [] notation, and so sizeof(array) is going to be sizeof(int*). array is really just a pointer to the first element, or possibly a pointer to a single integer allocated anywhere.

例如,我们可以这样调用 foo:

For example, we could call foo like this:

int x = 10;
foo(&x);

在这种情况下,foo 定义中的 [] 符号有点误导.

In which case the [] notation in the definition of foo is kind of misleading.

这篇关于C 指针表示法与数组表示法的比较:传递给函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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