【问题标题】:Passing array as pointer to function and using sizeof() operator [duplicate]将数组作为函数指针传递并使用 sizeof() 运算符 [重复]
【发布时间】:2017-05-28 07:28:48
【问题描述】:

我尝试使用独立函数获取为数组分配的字节数,但失败了。我的代码如下:

#include <stdio.h>

void testing(char *source);

int main(){

    char a[12] = "Hello World!";
    //printf("%d",sizeof(a));   Prints 12. I want to get this value
    testing(a); // Prints 4. I need to get 12 by using functions


return 0;
}

void testing(char *source){
    printf("%d",sizeof(source));
}

我想得到 12 的结果,但输出告诉我它是 4。

【问题讨论】:

  • 无法通过指针从sizeof 获取数组的大小。
  • 这就像说“我希望 2+2 为 5”。你可以继续“想要”它,但它不会发生。 sizeof 不会这样做。
  • 将函数改为void testing( char (*source)[12] ),然后在函数中使用sizeof *source

标签: c arrays pointers sizeof


【解决方案1】:

我想得到 12 的结果,但输出告诉我它是 4。

当数组作为指针传递给函数时,您无法获取数组的大小。

void testing(char *source) 中,source 是指针,所以sizeof( pointer ) 给你 4(你的机器中的 4 个字节)。

没有办法在函数内部找出数组大小,因为数组参数无论如何都会衰减为指针。

【讨论】:

  • 谢谢你!有没有其他方法可以做到这一点?
  • 除了以一种或另一种方式明确传递大小之外,别无其他。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多