[英]How to calculate the size of the statically allocated string in the calling function in C?
如何在函数 check_size 中获取值200
?
#include <stdio.h>
#include <string.h>
int check_size(char *ptr)
{
//if (sizeof(ptr) == 200)
//{
// ...
//}
printf("%ld \n", sizeof(ptr));
printf("%ld \n", sizeof(*ptr));
printf("%ld \n", strlen(ptr));
return 1;
}
int main()
{
char ptr[200]="\0";
int s = check_size(ptr);
return 0;
}
当数组用作函数参数时,它被转换为指向其第一个元素的指针。 因此,函数无法获取作为参数传递的数组的大小。
关于你的尝试:
printf("%ld \n", sizeof(ptr));
由于ptr
是一个char *
这将为您提供该指针的大小(通常为 8)。
printf("%ld \n", sizeof(*ptr));
这将为您提供ptr
指向的大小,特别是定义为 1 的char
。
printf("%ld \n", strlen(ptr));
假设ptr
指向一个空终止字符串,这将为您提供字符串的长度。
数组大小需要作为单独的参数传入,以便函数知道它。 如果在main
使用,则表达式sizeof(ptr)
将为您提供数组的大小(以字节为单位)。
如何在函数
check_size
获取值200
? 如何计算C中调用函数中静态分配字符串的大小?
由于ptr
的大小在编译时已知,并且您还应该在任何源代码中尽可能少地硬编码整数文字,只需使用宏常量来保存元素的数量。 有了它,您可以轻松地在函数check_size()
计算数组的大小:
#include <stdio.h>
#include <string.h>
#define length 200 // macro constant `length`.
int check_size(char *ptr)
{
printf("%zu \n", sizeof(*ptr)); // size of `char`
printf("%zu \n", sizeof(*ptr) * length); // size of the array.
printf("%zu \n", sizeof(ptr)); // size of the pointer to `char`.
printf("%zu \n", strlen(ptr)); // length of the string.
return 1;
}
int main()
{
char ptr[length] = "\0"; // macros can be used here.
check_size(ptr);
return 0;
}
输出:
1
200
8
0
需要澄清的一点:被调用函数没有“数组大小”的概念。 它给出的只是一个指向一个字节的指针。
现在,如果您要给数组一个特定的初始化,例如 199 个字符长度的字符串,您可以使用strlen()
。 或者您可以传入数组大小,尽管这很简单。
但总的来说,这里无法完全按照您的意愿行事。
如何在函数 check_size 中获取值 200?
与其有一个接受char*
函数,不如说有一个接受指向 char 数组 200 的指针的函数。
#include <stdio.h>
#include <string.h>
int check_size(char (*ptr)[200]) {
printf("%zu \n", sizeof(ptr));
printf("%zu \n", sizeof(*ptr));
printf("%zu \n", strlen(*ptr));
return 1;
}
int main() {
char ptr[200] = "\0";
check_size(&ptr);
return 0;
}
输出
8
200
0
燃气轮机
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.