C Define size of array inside main for a struct

130 views Asked by At

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

1

There are 1 answers

8
Tim On

Your global variable declaration for array_of_spheres is wrong, should be like below

SPHERE *array_of_spheres;