当前位置:网站首页>C陷阱与缺陷 第3章 语义“陷阱” 3.3 作为参数的数组声明
C陷阱与缺陷 第3章 语义“陷阱” 3.3 作为参数的数组声明
2022-07-29 02:48:00 【weixin_客子光阴】
作为参数的数组声明
在C语言中,我们无法将一个数组作为函数参数直接传递。如果我们将数组名作为参数,那么数组名会立刻被转换为指向该数组第1个元素的指针。例如,下面的语句:
char hello[] = "hello";
hello是一个字符数组。如果将该数组作为参数传递给一个函数:
printf("%s\n", hello);
实际上与该数组第1个元素的参数地址作为参数传递给函数的作用完全等效,即
printf("%s\n", &hello[0]);
因此,将数组作为函数参数毫无意义。所以,C语言中会自动地将作为参数的数组声明转换为相应的指针声明。也就是说,像这样的写法:
int strlen(char s[]) {
/*具体内容*/
}
与下面的写法完全相同:
int strlen(char *s) {
/*具体内容*/
}
extern char *hello;
这个语句与下面的语句有着天壤之别:
extern char hello[];
如果一个指针参数并不实际代表一个数组,即使从技术上而言是正确的,采用数组形式的记法也经常会起到误导作用。如果一个指针参数代表一个数组,情况有时如何呢?一个常见的例子就是函数main的第二个参数:
int main(int argc, char *argv[]) {
/*具体内容*/
}
这种写法与下面的写法完全等价:
int main(int argc, char **argv) {
/*具体内容*/
}
需要注意的是,前一种写法强调的重点在于argv是一个指向某数组的起始元素的指针,该数组的元素为字符指针类型。因为这两种写法是等价的,所以读者可以任选一种最能清楚反映自己意图的写法。
边栏推荐
猜你喜欢

Implementation principle of golang synergy

Confusion matrix learning notes

算法---粉刷房子(Kotlin)

VASP calculation task error: M_ divide:can not subdivide 8 nodes by 6

Analysis of Project-based Learning Creativity in steam Education

工科男生:20岁未满,平凡但不平庸

Weekly recommended short videos: how to make product development more effective?

Mysql复合查询(重要)

解读AI机器人养宠引领时尚潮流

Zone --- line segment tree lazy marking board sub problem
随机推荐
Analysis of concepts and terms in data warehouse
Unable to start after idea installation
万字详解 Google Play 上架应用标准包格式 AAB
Advanced architects, 16 common principles of microservice design and Governance
sqlilabs less-32~less-33
Trample --- discretization + tree array + difference
《QA离业务代码能有多近?》通过codediff直接暴露缺陷
idea配置web容器与war打包
C language: Little Lele and hexadecimal conversion
TP5.0 小程序用户无需登录,直接获取用户手机号。
解读AI机器人养宠引领时尚潮流
C language: hollow square pattern
数据截断及估计
Cloud development workers must go to work fishing and paddling wechat applet source code
C#从网址异步获得json格式的数据
centos安装mysql8
QT compilation of IOT management platform 48 characteristic function design
Summary of common hooks
【FreeSwitch开发实践】media bug获取通话语音流
【luogu P8352】小 N 的独立集(DP套DP)(性质)