【问题标题】:C Define size of array inside main for a structC为结构定义main内数组的大小
【发布时间】: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


【解决方案1】:

array_of_spheres 的全局变量声明错误,应如下所示

SPHERE *array_of_spheres;

【讨论】:

  • 不要翻译您的代码,将您的原始代码与原始问题一起发布。
  • 好的,我用西班牙语添加了代码.. 不明白它是如何产生任何尊重的,我只是将名称更改为更具可读性
  • @user2997958 你的 malloc 错误应该是这个lista_esferas = malloc(sizeof(*lista_esferas) * cantidad_de_esferas);
  • 我收到了这个新错误:RayT.c:40:68: error: invalid conversion from 'void*' to 'esfera*' [-fpermissive] lista_esferas = malloc(sizeof( *lista_esferas)* cantidad_de_esferas);
  • @user2997958 你在使用 c++ 编译器吗?
猜你喜欢
  • 2021-02-03
  • 2017-11-21
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2018-08-18
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多