gpt4 book ai didi

无法获取 arr[] : Implicit conversion loses integer precision: 'unsigned long' to 'int' for strlen(arr) 的长度

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

隐式转换会丢失整数精度:
'unsigned long' 到 'int'

我想获取单词的长度[]但它告诉我这个。我该如何解决?

int main(int argc, const char * argv[]) {

char test[] = "ls test";
f_sparce_arg(test);
return 0;
}
char * f_sparce_arg(char words[]){
int words_length;
words_length = strlen(words); /* warning: Implicit conversion
integer precision: 'unsigned
long' to 'int' */

printf("%d", words_length);
return "";
}
// warning: Implicit conversion integer precision: 'unsigned long' to 'int'

最佳答案

什么 strlen function返回的是 size_t,所以你应该用它来存储它的返回值。

char * f_sparce_arg(char words[]){
size_t words_length; /* use proper type */
words_length = strlen(words);

printf("%zu",words_length); /* the format to print size_t value is %zu */
return "";
}

不幸的是,某些编译器或库不支持 %zu 格式。另一种方法是,如果字符串不会太长,则将返回值转换为 int

char * f_sparce_arg(char words[]){
int words_length;
words_length = (int)strlen(words); /* explicitly cast the result to avoid warnings */

printf("%d",words_length);
return "";
}

关于无法获取 arr[] : Implicit conversion loses integer precision: 'unsigned long' to 'int' for strlen(arr) 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58250216/

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