我不明白C中的数组衰减..它似乎是选择性的

问题描述 投票:0回答:1

当我在函数指针中传递 B[2][3] 2D 数组时,预期会衰减。

然而,这似乎仅在我作为语法参数传递的内容中选择性地发生。

这是我的代码:

#include<stdio.h>


void printArray(int B[][3])
{
     printf("sizeof(B) is : %u\n", sizeof(B)); //When arrays are passed to functions they decay into pointers. 
     printf("sizeof(B[0]) is : %u\n", sizeof(B[0])); //But here I get an array-pointer.Why there is no array to pointer decay here?See results Below.
    
}




int main(int argc, char* argv[])
{
    int B[2][3] = { {2,3,6},{4,5,8} };
    
    printf("sizeof(B) is : %u\n", sizeof(B));
    printf("sizeof(B[0]) is : %u\n", sizeof(B[0]));

    printArray(B);

    return 0;
}

这是我的结果:

sizeof(B) is : 24
sizeof(B[0]) is : 12
sizeof(B) is : 4
sizeof(B[0]) is : 12

C:\Users\Strakizzz\Desktop\C\My Codeschool Projects\Pointers in C?C++\Debug\FunctionsPointersScopeMayhem.exe (process 20660) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

我期望在从我调用的函数中打印 sizeof(B[0]) 时也能获得 4 个字节,就像我在同一函数中计算 sizeof(B) 时一样:

void printArray().

.为什么我会得到这些结果,幕后发生了什么?

arrays c sizeof
1个回答
0
投票

数组“衰减”发生在许多使用数组类型的上下文中,它用指向数组第一个元素的指针替换数组类型。所以

int a[5]
会衰减为
int *

对于二维数组,即数组的数组,它的工作原理如下:

int B[2][3]
衰减为
int (*)[3]
,它是指向三个
int
的数组的指针。这是因为 B 是一个包含两个元素的数组,每个元素都是一个包含三个
int
的数组。

printArray
中,编译器自动调整
B
为类型
int (*B)[3]
B
是一个指针,在您的机器上其大小为
4
,并且
B[0]
的类型为
int [3]
,因此它的大小为
sizeof(int) * 3
,在您的机器上为 12。因此
printArray
打印 4 和 12。

可移植性注意事项:使用

%u
打印
sizeof
值(其类型为
size_t
)是不可移植的。相反,请使用
%zu
,它是便携式的。

© www.soinside.com 2019 - 2024. All rights reserved.