是一个数组参数传递给函数不是一个常量指针? [英] Is an array argument passed to a function not a constant pointer?

查看:102
本文介绍了是一个数组参数传递给函数不是一个常量指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑code:

 无效美孚(CHAR一个[]){
   一个++; //工作正常,被编译
   // ...
}

现在,考虑一下:

 无效美孚(){
   所以char a [50];
   一个++; //编译器错误
   // ...
}

我听到的阵列相当于一个恒定指针,并且不能增加,因为它不是一个左值...

那么,为什么不先code被编译,是不是如此,因为数组函数的参数作为一个指针传递,即T []被转换为T *传递..
因此,美孚(一)传递一个作为指针。

但是,它不回转换为T []又因为被声明为:

 无效美孚(CHAR一个[]);


解决方案

当你传递一个数组作为参数传递给一个函数,它衰变为指针。结果
所以,你在函数体中增加的东西是一个指针,而不是一个数组。

Consider the code:

void foo(char a[]){
   a++;            //  works fine, gets compiled
   //... 
}

Now, consider this:

void foo(){
   char a[50];
   a++;            //  Compiler error
   //... 
}

I heard an array is equivalent to a constant pointer and can't be incremented as it is not a lvalue...

Then why does first code gets compiled, is it so because array arguments to functions are passed as a pointer, i.e. T[] is converted to T* for passing.. So, foo(a) passes a as a pointer.

But is it not back converted to T[] again because is declared as:

void foo(char a[]);

解决方案

When you pass an array as an argument to a function, it decays to a pointer.
So the thing you increment inside the function body is a pointer, not an array.

这篇关于是一个数组参数传递给函数不是一个常量指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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