繁体   English   中英

声明数组并使用malloc时出现ISO C90错误

[英]ISO C90 error while declaring an array and using malloc

我刚刚学习了动态内存分配,所以我尝试对其进行测试。 我正在使用具有以下构建配置的sublime text 3

 {
"cmd": ["gcc", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o", "${file_base_name}.exe", "&&", "start", "cmd", "/k" , "$file_base_name"],
"selector": "source.c",
"working_dir": "${file_path}",
"shell": true
 }

我已经在codeblocks bin文件夹的path变量中包含了gcc编译器的路径

C:\\ Program档案(x86)\\ CodeBlocks \\ MinGW \\ bin

我曾经尝试运行的C代码看起来像这样...

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n,i;
    scanf("%d",&n);
    int *order=(int*)malloc(sizeof(int)*n);

    for(i=0;i<n;i++)
        scanf("%d",&*(order+i));

    printf("%d",order[2]); /*just seeing whether output is properly displayed or not */

    return 0;
}

崇高文字显示的错误是:

8:2: error: ISO C90 forbids mixed declarations and code [-pedantic]

我尝试在代码块中运行我的代码,它运行完美。 所以有什么办法可以使用崇高的文字3本身在C99中而不是C90中运行我的C程序

您不会使用给定的标准 运行程序,而是使用规则编译它们。

文本编辑器与此无关。 要解决此问题,请从此列表中将-ansi标志替换为-std=c99

"cmd": [
        "gcc", 
        "-Wall", 
        "-std=c99",
        "-pedantic-errors",
        "$file_name", 
        "-o", "${file_base_name}.exe", 
        "&&", 
        "start", 
        "cmd", 
        "/k" , 
        "$file_base_name"
]

为了使代码更清晰,您只能在块的开头声明变量,这就是错误所在。 ,禁止将声明与代码混合使用。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n;
    int i;
    int *order
    if (scanf("%d", &n) != 1)
        return -1;
    order = malloc(sizeof(*order) * n);
    for (i = 0 ; i < n ; i++)
        scanf("%d", order + i); // Please check the return value here too/
    printf("%d", order[2]); // This might invoke UB because you ignored
                            // `scanf()'s return value in the loop.
    return 0;
}

所以宣言

int *order = ...

导致错误,将其移至程序段开头即可解决。

另外,请注意,您无需将malloc()的返回值malloc()转换为目标指针类型,并且通常void *将自动转换为目标指针类型。

所以有什么办法可以使用崇高的文字3本身在C99中而不是C90中运行我的C程序

设置标志-std=c99

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM