在函数参数数组中放置一个大小的意义是什么?

时间:2023-01-20 21:47:07
int main()
{
    int iStrangeArrayOutter[11];
    iStrangeArrayOutter[7] = 5; 
    testFunc (iStrangeArrayOutter);
    return 0;
}

int testFunc (int iStrangeArray[3])
{
    printf ("%d\r\n", iStrangeArray[7]);
    return 0;
}

What does the int iStrangeArray[3] part of the function declaration reveal?

函数声明的int iStrangeArray [3]部分揭示了什么?

2 个解决方案

#1


2  

Arrays are automatically converted to a pointer to its first element when used as function argument, so this function signature:

当用作函数参数时,数组会自动转换为指向其第一个元素的指针,因此此函数签名:

int testFunc(int iStrangeArray[3])

is equivalent to:

相当于:

int testFunc(int iStrangeArray[])

or

int testFunc(int *iStrangeArray)

The size of the array is ignored, it's only useful as a signal to the programmer, not to the compiler. As for the why, because it's what the C standard says.

数组的大小被忽略,它仅作为程序员的信号,而不是编译器。至于原因,因为这是C标准所说的。

#2


1  

That may be a hint to readers that the length of iStrangeArray should be three, therefore it could act like part of the API documentation.

这可能暗示读者认为iStrangeArray的长度应为3,因此它可以作为API文档的一部分。

However, just like any other documentations that cannot be verified by compilers (or other tools), when the related code evolved, documentations and the code they tried to explain may become asynchronous, at this time (and it looks like this is exactly what happened in your case), this "documantation" could become misleading and will confuse readers.

然而,就像编译器(或其他工具)无法验证的任何其他文档一样,当相关代码发展时,他们试图解释的文档和代码可能会变成异步(此时看起来这正是发生的事情)在你的情况下),这种“文件记录”可能会误导,并会使读者感到困惑。

#1


2  

Arrays are automatically converted to a pointer to its first element when used as function argument, so this function signature:

当用作函数参数时,数组会自动转换为指向其第一个元素的指针,因此此函数签名:

int testFunc(int iStrangeArray[3])

is equivalent to:

相当于:

int testFunc(int iStrangeArray[])

or

int testFunc(int *iStrangeArray)

The size of the array is ignored, it's only useful as a signal to the programmer, not to the compiler. As for the why, because it's what the C standard says.

数组的大小被忽略,它仅作为程序员的信号,而不是编译器。至于原因,因为这是C标准所说的。

#2


1  

That may be a hint to readers that the length of iStrangeArray should be three, therefore it could act like part of the API documentation.

这可能暗示读者认为iStrangeArray的长度应为3,因此它可以作为API文档的一部分。

However, just like any other documentations that cannot be verified by compilers (or other tools), when the related code evolved, documentations and the code they tried to explain may become asynchronous, at this time (and it looks like this is exactly what happened in your case), this "documantation" could become misleading and will confuse readers.

然而,就像编译器(或其他工具)无法验证的任何其他文档一样,当相关代码发展时,他们试图解释的文档和代码可能会变成异步(此时看起来这正是发生的事情)在你的情况下),这种“文件记录”可能会误导,并会使读者感到困惑。