c - 声明数组和使用 malloc 时出现 ISO C90 错误

标签 c sublimetext3 c99

我刚刚学习了动态内存分配,所以我尝试对其进行测试。我正在使用具有以下构建配置的 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 文件夹的路径变量中包含了 gcc 编译器的路径

C:\Program Files (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;
}

sublime text 显示的错误是:

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

I tried running my code in codeblocks and it works perfectly. so is there any way by which i can run my c programs in C99 instead of C90 using sublime text 3 itself

最佳答案

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

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

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

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

#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 = ...

导致错误,将其移至 block 的开头即可解决。

此外,请注意,您不需要将 malloc() 的返回值转换为目标指针类型,通常 void * 会自动转换为目标指针类型。

关于c - 声明数组和使用 malloc 时出现 ISO C90 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708492/

相关文章:

c - 使用 select() 和 O_NONBLOCK 从 FIFO 读取两个连续写入

python - Sublime Text 设置问题 : Code Not Running

C - 标准输入、unix 管道和 EOF

C 数组值有时会被取反

c - zlib Z_DATA_ERROR "invalid code lengths set"

javascript - 如何在 Sublime 3 中设置 JavaScript?

c - c99和c11的区别

linux - SA_RESTART 未在 Linux 下定义,在 Solaris 中编译良好

c - 函数名称存储在 ARM7l 堆栈帧中的位置(不是链接寄存器 0x​​104567910 中的函数地址)

css - Sublime Text CSS 奇数对象语法突出显示 - 插件存在吗?