void reverses(char s[])
{
int i, count;
i = count = 0;
// Get the total character count in array
while (s[count] != '\0') ++count;
char copy[count];
只有在直接使用整数时才会定义 Char 数组复制,例如 char copy[15];
或 char copy[DEFINED];
。
我通过 int count;
向它传递一个整数,它有一个声明值,那么为什么我的数组没有被定义?
我在复制到这里后发现我的代码有错误,抱歉。
我当时使用 while 循环来进行反转——将其更改为 for 循环解决了问题。
无论如何,您的许多回答对我很有帮助。所以,谢谢 David Cullen , Vlad from Moscos , R Sahu , user0815 , 和 haccks
Vlad 的回答非常棒,感谢您启发我——我会认真考虑您的回答。 David Cullen 完全按照我的逻辑得出了正确答案!
最佳答案
这段代码产生了预期的输出:
#include <stdio.h>
void reverses(char s[])
{
int i, count;
i = count = 0;
while (s[count] != '\0') ++count;
printf("count = %d\n", count);
char copy[count + 1];
for (i = 0; i < count; i++) {
copy[count - i - 1] = s[i];
}
copy[count] = '\0';
printf("copy = %s\n", copy);
}
int main(void)
{
reverses("string");
}
输出:
count = 6
copy = gnirts
这是在 OS X 上用 gcc 测试的:
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix
关于C 字符数组定义长度使用变量不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310344/