简体   繁体   中英

C Define size of array inside main for a struct

I looked at like 5 posts and still can't figure if this is possible....

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);
  .
  .
  .
  .
}

As you see I need list_of_spheres to be global, but I don't know the size until I read the file, so how can I initialize this array?

error: expected primary-expression before ‘)’ token
array_of_spheres = malloc(sizeof(SPHERE)*number_spheres);

I tried sizeof(SPHERE) AND sizeof(*SPHERE) .

The original code is in spanish in the .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;

in the .c after i read a file and figure the number of spheres:

lista_esferas = malloc(sizeof( *esfera)*cantidad_de_esferas);

                               ^

RayT.c:29:40: error: expected primary-expression before ')' token lista_esferas = malloc(sizeof( *esfera)*cantidad_de_esferas);

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

SPHERE *array_of_spheres;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM