c - 通过将数组作为参数传递给函数来增加数组的大小

标签 c arrays pointers implicit-conversion

#include<stdio.h>
void fun1(int a[100])
{
  a[4]=1;
}
void main()
{
   int a[2]={1,2};
   fun1(a);
   printf("%d",a[4]);   // Output 1
}

我知道当我们将数组作为函数参数传递时,数组会衰减为指向第一个元素的指针。但是 main 函数中数组的大小是如何增加的呢?

最佳答案

根据C标准(6.7.6.3函数声明符(包括原型(prototype)))

7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation....

这意味着在声明中

void fun1(int a[100])
{
  a[4]=1;
}

函数参数被调整为类型int *,因此函数实际上具有以下声明

void fun1( int *a )
{
  a[4]=1;
}

例如以下函数声明

void fun1(int a[2]);
void fun1(int a[10]);
void fun1(int a[100]);

声明与声明类似的同一个函数

void fun1(int *a);

另一方面,在表达式中用作函数参数的数组会隐式转换为指向其第一个元素的指针。因此,在此函数中,使用数组指示符调用表达式

fun1(a);

数组指示符a被转换为指向其第一个元素的指针,并且参数的表达式的类型为int *

你可以通过以下方式想象这个调用

{
    int *temporary p = a;
    fun1( p );
}    

因此函数参数的类型为int *,即它是一个指针,相应的参数也是一个指针。该函数不处理数组类型的对象。它处理指针类型的对象。

因此,两个数组都不会增加其大小,并且原始程序具有未定义的行为,因为试图访问原始数组之外的内存。

您可以通过输出参数的大小轻松检查该函数是否处理指针。例如

void fun1(int a[100])
{
    printf( "sizeof( a ) = %zu\n", sizeof( a ) );
    a[4]=1;
}

输出将等于48,具体取决于所使用的系统。但无论如何,它都不会如您所期望的那样等于 100 * sizeof( int )

关于c - 通过将数组作为参数传递给函数来增加数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904256/

相关文章:

c - 数组被删除

c - 在 linux 中修改目标文件函数 xref 的优雅方式

ruby - 划分数组以创建多维数组

c - scanf() 将换行符保留在缓冲区中

c - 如何将子矩阵作为指针传递给另一个函数

javascript - fs.createReadStream 之后代码块未执行

sql - 如何在 Postgresql 中将数组拆分为行

c - 取消引用指针错误

c++ - 不处理指针时调用子类(虚拟)函数(后期绑定(bind))

c++ - 确保返回值不是指针