【发布时间】:2015-08-26 13:51:14
【问题描述】:
我看了大约 5 个帖子,但仍然无法确定这是否可能......
typedef struct {
long double xc;
long double yc;
long double zc;
long double radio;
long double Kd;
long double Ka;
long double Ks; // specular
color fc;
} SPHERE;
// *array_of_spheres; // Original line omitted SPHERE
SPHERE *array_of_spheres;
int main(int argc, char** argv) {
int number_spheres = read_file();
//this return the number of spheres in the text file after fscanf
array_of_spheres = malloc(sizeof(SPHERE)*number_spheres);
.
.
.
.
}
如您所见,我需要 list_of_spheres 是全局的,但在读取文件之前我不知道大小,那么如何初始化这个数组?
error: expected primary-expression before ‘)’ token
array_of_spheres = malloc(sizeof(SPHERE)*number_spheres);
我试过sizeof(SPHERE) 和sizeof(*SPHERE)。
原始代码是西班牙语 在.h
typedef struct
{
long double xc;
long double yc;
long double zc;
long double radio;
long double Kd;
long double Ka;
long double Ks; // especular
color fc;
}esfera;
esfera *lista_esferas;
在我读取文件并计算球体数量后的 .c 中:
lista_esferas = malloc(sizeof( *esfera)*cantidad_de_esferas);
^
RayT.c:29:40: 错误: ')' 标记之前的预期主表达式 lista_esferas = malloc(sizeof(*esfera)*cantidad_de_esferas);
【问题讨论】:
-
错误建议!并且不要投射
malloc(),这是不好的做法。 -
您的西班牙代码与您的英语代码不匹配。为什么
sizeof( *esfera)中有*?*在那里做什么?它应该只是sizeof(esfera)或更好的sizeof *lista_esferas。 -
您需要
sizeof(esfera)或sizeof(*lista_esferas)或sizeof(lista_esferas[0])。您不能取消对非指针的引用,esfera是普通结构类型,而不是指针类型。
标签: c initialization malloc global sizeof