为什么下一个公式在main中计算出正确的值但在函数中计算出错误的值?

问题描述 投票:0回答:0
#include <iostream>

@brief calculates and prints array size
@param string the array
void function(char* string){
int n = sizeof(string)/sizeof(char); //should be size of the array given
printf("%d",n); //prints INCORRECT size - 8
}

int main(){
char str[] = "abcd"; //size is 5
printf("%d",(sizeof(str)/sizeof(char)); //prints correct size - 5
}

问题:

当我尝试计算代码中公式给出的数组的大小时,它在 main 和任何函数中返回不同的值。主块中的结果是正确的,但在任何功能块中,它计算出错误的值。为什么?

我尝试计算数组的大小,并期待得到它。

c++ arrays sizeof
© www.soinside.com 2019 - 2024. All rights reserved.