You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenGL教程代码存疑?数组大小非常量表达式无法编译

问题解答

这段代码确实存在可移植性缺陷,属于教程中的代码问题,并非你遗漏了知识点,具体分析如下:

核心原因

C标准(涵盖C11到C20)不支持变长数组(VLA)——即数组的大小不能是运行时才能确定的表达式(比如strlen(text)的结果要在程序运行时计算)。虽然C99标准引入了变长数组特性,但该特性并未被纳入C标准,仅部分编译器(如GCC、Clang)提供了非标准扩展支持。如果你的编译环境未启用该扩展,或使用严格遵循C++标准的编译器(如MSVC),这段代码必然编译失败。

标准兼容的修正方案

可以用以下两种方式替代原代码:

1. C++标准容器(推荐)

使用std::vector管理动态数组,既安全又符合标准:

#include <vector>

struct point {
    GLfloat x;
    GLfloat y;
    GLfloat s;
    GLfloat t;
};

std::vector<point> coords(6 * strlen(text));

2. 动态内存分配(C/C++通用)

通过malloc/free(C)或new/delete(C++)手动管理内存:

// C++实现方式
struct point {
    GLfloat x;
    GLfloat y;
    GLfloat s;
    GLfloat t;
};

point* coords = new point[6 * strlen(text)];
// 使用完毕后务必释放内存
delete[] coords;

内容的提问来源于stack exchange,提问作者JGondek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:05:58