gpt4 book ai didi

C 中全局结构中的 const 变量

转载 作者:行者123 更新时间:2023-11-30 17:41:52 24 4
gpt4 key购买 nike

我正在尝试在 C 中的全局结构内定义一组常量变量。到目前为止,我有一个头文件“params.h”:

#ifndef PARAMS_H_INCLUDED
#define PARAMS_H_INCLUDED

typedef struct Params_s {

const int nSamples;
//Some other constants here...

} Params;

extern const Params params;

#endif

我还有一个文件“params.c”来定义我的常量:

#include "params.h"

Params params = {

8*1024, // nSamples
//Some other constants here...

}

当我尝试使用这些常量来定义数组大小等内容时,就会出现问题。如果在第三个 .c 文件中我写:

#include "params.h"

//...Code here...

double p[params.nSamples];

然后我最终在数组大小上出现以下错误:

IntelliSense: expression must have a constant value

我是否错误地声明了我的常量?

最佳答案

是的。这意味着它应该使用像 2, 3, 10 这样的值,而不是像变量 n

据我所知,您的值(value)是恒定的,因此您可以使用

#define NSAMPLES 8192

并使用类似

double p[NSAMPLES];

更好的方法是动态分配

double* p = malloc(sizeof(double)*params.nSamples);

关于C 中全局结构中的 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20971316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com