C 字符数组定义长度使用变量不工作

标签 c arrays char

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/

相关文章:

arrays - 将二维数组旋转 90 度

java - 无法读取重复字符

c - .bmp 图像比较显示 image.bmp 上的 EOF

c - 强制读取 volatile 变量

javascript - 谷歌表格: Return Multi Dimensional Array (JavaScript)

c - 在 char 类型变量中声明 'a' 但 'b' 作为输出出现,有什么问题吗?

sql-server - SQL 服务器 : Auto increment char pk

c - 附加到正在运行的进程的分析器?

c - 为什么下面代码中的 for 循环不作为无限循环运行(我在 -1 之后继续作为 1 2 3...-3 -2 -1)?

arrays - 按字母顺序添加到字符串数组