Invalid initialization error with structure

I have two structures, one of which is basic, position_3d. The other is a ray.

typedef struct{
float x,y,z;    
} position_3d;

typedef struct{
vector_3d direction;
position_3d startPosition;  
} ray;

I implemented a function that returns position_3d struct

position_3d getIntersectionPosition(ray r, sphere s){
    position_3d pos; 
    //some code

    pos.x = r.startPosition.x + t*r.direction.x; 
    pos.y = r.startPosition.y + t*r.direction.y; 
    pos.z = r.startPosition.z + t*r.direction.z;  
    return pos; 
}

when i call

position_3d pos = getIntersectionPosition(r, s);

I received this error with an invalid initializer. I am using gcc. The compilation command is gcc prog.c -o prog.out -lm -lGL -lGLU -lglut

I'm really stuck now! Can anyone help?

+3
source share
3 answers

The problem was in the wrong order of functions. I mean, I need to determine the signature of all functions before calling them.

0
source

Is the string

position_3d pos = getIntersectionPosition(r, s);

in the file area (then this is an error because the initializer is not a constant) or the block area (then it should work)?

+2
source

, , , :

  • sphere?
  • vector_3d?
  • t?

, ( sphere.c):

typedef struct
{
    float x,y,z;
} position_3d;

typedef struct
{
    float x, y, z;
} vector_3d;

 typedef struct
{
    vector_3d direction;
    position_3d startPosition;
} ray;

typedef struct
{
    float radius;
    position_3d centre;
} sphere;

position_3d getIntersectionPosition(ray r, sphere s)
{
    position_3d pos;
    float t = s.radius;

    pos.x = r.startPosition.x + t*r.direction.x;
    pos.y = r.startPosition.y + t*r.direction.y;
    pos.z = r.startPosition.z + t*r.direction.z;
    return pos;
}

position_3d func(ray r, sphere s)
{
    position_3d pos = getIntersectionPosition(r, s);
    return pos;
}

, :

$ /usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
       -Wold-style-definition -c sphere.c
sphere.c:24: warning: no previous prototype for ‘getIntersectionPosition’
sphere.c:35: warning: no previous prototype for ‘func’
$

; -Wmissing-prototypes. , .

, , . C , :

ray         r;
sphere      s;
position_3d pos = getIntersectionPosition(r, s);

position_3d func(void)
{
    return pos;
}

:

sphere.c:43: error: initializer element is not constant

g++ gcc ( C- , ):

$ g++ -O3 -g -Wall -Wextra -c sphere.c
$

cleanly — , C ++ - , , .

, , , , . , , . , :

  • , , . , , ( , , , , ( ), GL). C POSIX , .
  • ( ).
  • Show the exact compiler warnings you get under this strict set of C compilation options. (This means that for the absence of previous prototypes there should be at least two warnings. But there must also be an error, the one you require does not allow your code to work. ) We should be able to match the line numbers in your error messages trivially for the code you are showing.
+1
source

All Articles