C指针,指向符号相比,数组的方式:当传递给函数 [英] C pointer notation compared to array notation: When passing to function

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

问题描述

我的问题是在以下code基:

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.

我的precise的问题,是没有任何理由使用指针符号,因此使用的指针操作函数内传递一个数字阵列功能。

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中,当你传递一个数组变量给一个函数,它衰变为指针不管记号。然而,在我看来,在指针符号是preferable 。这个问题 [] 符号函数定义是这样的,在我看来,这是有点误导:

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(阵列)会给你的乘以元素的数组中的数的sizeof(INT),就像它将如果阵列是在栈上声明数组变量。但现实是,阵列已衰减到一个指针,的尽管的误导 [] 记法,所以的sizeof(阵列)将是的sizeof(INT *)阵列其实只是一个指向第一个元素,或者可能指向任何地方分配的一个整数。

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.

例如,我们可以称之为是这样的:

For example, we could call foo like this:

int x = 10;
foo(&x);

在这种情况下,在定义的 [] 标记是一种误导。

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

这篇关于C指针,指向符号相比,数组的方式:当传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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