首页 > 解决方案 > 初始化元素不是 malloc 的编译时常量

问题描述

我正在编写一个 C 程序,但 pvowels 指针出现以下错误:

[cquery] initializer element is not a compile-time constant

这是代码:

int n = 5;
char *pvowels = (char *) malloc(n * sizeof(char));

pvowels[0] = 'A';
pvowels[1] = 'E';
*(pvowels + 2) = 'I';
pvowels[3] = 'O';
*(pvowels + 4) = 'U';

for(int i = 0; i < n; i++) {
    printf("%c ", pvowels[i]);
}

printf("\n");

free(pvowels);

标签: c

解决方案


在 C 中,所有可执行代码都必须驻留在函数中。只有带有常量初始化器的变量声明可以存在于函数之外。

将此代码放在main函数中,这是 C 程序的起点。此外,您还需要#include针对您正在使用的功能的相关指令。

#include <stdio.h>      // for printf
#include <stdlib.h>     // for malloc,free

int main()
{
    // you code here
    return 0;
}

推荐阅读