gpt4 book ai didi

c - 字符串创建问题 C

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:18 25 4
gpt4 key购买 nike

我想创建一个函数来创建一个具有特定长度的新字符串。这是代码:

char* newString(int lenght){

char* newstring =(char*)((calloc(lenght, sizeof(char))));
newstring[lenght] = '\0';
return newstring;
}

我是这样使用的:

char* string = newString(10);

我的问题是当我这样做时:

printf("String lenght  %lu \n",strlen(string));

我得到 0,但我不明白为什么。我是 C 的新手。感谢您的宝贵时间

最佳答案

strlen 返回第一个 '\0' 之前的字符数。如果您使用:

char s[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int len = strlen(s); // len will be zero.

关于c - 字符串创建问题 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com