【发布时间】:2021-01-02 21:52:46
【问题描述】:
我在 C 中定义了一个函数如下:
int *face_2_cells(int boundary_field_id) {
int b_cells_field[4];
if(boundary_field_id==1)
{
b_cells_field[0]=1;
b_cells_field[1]=2;
b_cells_field[2]=3;
b_cells_field[3]=4;
}
else{
b_cells_field[0]=0;
b_cells_field[1]=0;
b_cells_field[2]=0;
b_cells_field[3]=0;
}
return b_cells_field;
}
然后我在另一个函数中调用了这个函数,然后打印出数组的大小,如下所示:
void
cs_user_extra_operations()
{
{
int *face_22_cells = face_2_cells(1);
printf("\n SIZE = %i"" ", sizeof(face_22_cells)/sizeof(face_22_cells[0]));
}
}
但代码输出 SIZE = 2,而 SIZE 的正确值是 4。 问题出在哪里?
【问题讨论】:
-
您的函数还返回一个指向不再存在的数组的指针,因此在上一个副本之上,您的代码也被破坏了
-
sizeof(face_22_cells) 返回指针的大小,而不是它所指向的大小。所以如果你有一个 64 位指针(大小 8)和 /sizeof(int) (4) 你得到 2。
-
您在这里遇到的另一个问题(与问题无关)是您返回对本地数组的引用,当您退出函数时该数组不再存在。