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

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

问题描述

考虑代码:

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

现在,考虑一下:

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...

那么为什么要编译第一个代码,是不是因为函数的数组参数作为指针传递,即 T[] 被转换为 T* 以传递..因此,foo(a) 将 a 作为指针传递.

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.

但是它不是再次转换回 T[] 因为声明为:

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天全站免登陆