Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 这个语法正确吗?_C - Fatal编程技术网

C 这个语法正确吗?

C 这个语法正确吗?,c,C,在过去的几天里,我一直在使用Coderbyte.com解决C语言中的一些编码难题。我通常使用代码块作为IDE,我注意到有时Coderbyte IDE中的工作解决方案会在代码块中抛出错误。 例如: #include <stdio.h> #include <string.h> void AlphabetSoup(char str[]) { int i, j, length; length = strlen(str); char new_strin

在过去的几天里,我一直在使用Coderbyte.com解决C语言中的一些编码难题。我通常使用代码块作为IDE,我注意到有时Coderbyte IDE中的工作解决方案会在代码块中抛出错误。 例如:

#include <stdio.h>
#include <string.h>

void AlphabetSoup(char str[]) {
    int i, j, length;

    length = strlen(str);

    char new_string[length];
    char temp;

    strcpy(new_string, str);

    for (i = 0; i < length; i++) {
        for (j = i + 1; j < length; j++) {
            if (new_string[i] > new_string[j]) {
                temp = new_string[i];
                new_string[i] = new_string[j];
                new_string[j] = temp;
            }
        }
    }

    // code goes here
    printf("%s", new_string);
}

int main(void) {
    AlphabetSoup(gets(stdin));
    return 0;
}
无论如何,我不明白为什么这个解决方案在一个IDE上工作,而不是在另一个IDE上工作。另一次,我输入的一些代码说它只能在C99中工作

现在,当我在代码块中运行此代码时,它会崩溃,但不会在Coderbyte上崩溃

我的问题是:

1) 有不同版本的C吗

2) 此代码是否仍然正确,还是最好对函数参数使用
char*

我对C还是新手

1) 有不同版本的C吗

是的,这段代码的有效性在不同的C标准中有所不同的具体原因是您正在使用函数
get
,该函数已被弃用,后来被现代C标准完全删除。实际上,在生产代码中使用
gets
是无法避免缓冲区溢出的,因此建议使用检查缓冲区长度的函数<代码>fgets最常见于:

fgets(buffer, BUFFER_SIZE, stdin);
2) 这段代码还是正确的,还是最好使用char*作为函数参数


函数参数之间没有区别:
char*foo
char foo[]
,因为当数组作为参数传递给函数时,它会衰减为指向其第一个元素的指针。这两种语法都可以接受。

此语法不正确,因为c/c++中的数组声明在编译时必须具有常量大小

length = strlen(str);

char new_string[length];
无法在编译时确定长度值。如果要在运行时控制大小,则必须在C中使用mallocnew操作符(C++)


请参见

获取
需要字符串缓冲区,它也不接受流,只有
fgets
接受文件流。!)是的,当然。2)
获取
。您需要它是
char new_字符串[length+1]。否则,您将使用strcpy
strcpy
在缓冲区的末尾写入一个。是否很难看到get获取另一个类型参数?简单的google“gets”会立即给出答案。C99支持VLA的。除van的评论外,这是C,所以会使用malloc,而不是newI。我会说其中一个问题不值得回答。OP并没有费心去查看函数原型,看看它需要什么参数。顺便说一句,在这一级别的C知识中,代码的安全性是次要的——对于生产代码来说还为时过早
length = strlen(str);

char new_string[length];