【发布时间】:2020-10-16 22:26:08
【问题描述】:
在 C 而不是 C++ 中,我尝试使用包含在 const int 中的 strlen() 来设置 char 数组大小。
char *input = "hello";
//now the integer that contains the lenght
static const int lengthA = strlen(input); //upto here, it works
char list_array[lengthA]; //here doesn't work, because the variable lengthA is not initialized
所以,我希望 input 的长度用作 array 的长度。
我已经尝试使用 sizeof,而不是 strlen,但它返回字节
这可能吗?
【问题讨论】:
-
如果您的编译器支持可变长度数组,那么提供的代码是有效的,前提是关键字 static 将被删除为常量 lengthA。
-
这段代码到底发生了什么?如果有的话,您会收到哪些错误消息?另外,你用的是什么编译器?是偶然的 MSVC 吗?
-
我正在使用 VS,错误是“错误 C2131:表达式未计算为常量”。但微软网站对我没有帮助。
-
请记住,
strlen("hello")字符数组不足以容纳字符串"hello"。如果要将字符串"hello"存储在list_array中,则需要为'\0'终止符再分配一个字节。 (您可以将字符'h', 'e', 'l', 'l', 'o'存储在5 个字节中,但是list_array的内容将不是字符串,并且对其应用的任何字符串操作都将是未定义的。) -
请编辑您的问题以包含错误消息
标签: arrays c pointers char string-length