c - 初始化元素不是 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 中,所有可执行代码都必须驻留在函数中。只有带有常量初始化器的变量声明可以存在于函数之外。
将此代码放在main
函数中,这是 C 程序的起点。此外,您还需要#include
针对您正在使用的功能的相关指令。
#include <stdio.h> // for printf
#include <stdlib.h> // for malloc,free
int main()
{
// you code here
return 0;
}
推荐阅读
- python - “从 numpy.core._multiarray_umath 导入”抛出错误“DLL 加载失败:找不到指定的模块。”
- isabelle - 我如何证明一个对象不解释语言环境?
- botframework - Microsoft Botframework:并发测试失败
- django - 如何在 Django TemplateDoesNotExist 中查找问题
- javascript - 使用原始查询时,Sequelize 无法识别带有 camelCase 名称的表
- javascript - 显式 .trigger("click") 未设置为 true jquery
- python - 如何使用 Kivy 中的按钮打开文件示例(pdf 文件)
- c++ - next_permutation 不是通过引用?
- java - Java类加载器getResource在一段时间后失败
- angular - 401 Unauthorized with Ionic 5 + Angular 9 with POST request