Array of Objects C?

Started by
4 comments, last by DevFred 14 years, 7 months ago
I have created objects to define a particle and am trying to print out there location values but it doesn't seem to be printing out the correct values. what am i doing wrong?

#include <stdlib.h>
#include <stdio.h> 




static particles = 10;

typedef struct {
       double locx; 
       double locy;
       double locz;
       double vecx;
       double vecy;
       double vecz;
} Particle;

Particle make_particle (double locationx, double locationy, double locationz);
void display_particle (Particle theParticle);



Particle make_particle (double locationx, double locationy, double locationz)
{
     Particle newParticle;
     
     newParticle.locx = locationx;
     newParticle.locy = locationy;
     newParticle.locz = locationz;
     
     return newParticle;         
}

void display_particle(Particle theParticle)
{
     printf("%d, %d, %d\n", theParticle.locx, theParticle.locy, theParticle.locz);
}

double get_locx(Particle theParticle)
{
    
     return theParticle.locx;
}

double get_locy(Particle theParticle)
{
    
     return theParticle.locy;
}
double get_locz(Particle theParticle)
{
    
     return theParticle.locz;
}






/* GLUT callback Handlers */




main()
{
    
    Particle myArray[particles];
    int i, j;
    double v = 0, v2 = 0;
    for (i =0; i<particles; i = i + 1)
    {
        v= v+0.001;
        v2 = v2 + 0.001;
        Particle part = make_particle(v, v2, 0);
        myArray = part;
    }
    
    for (j =0; j<particles; j = j + 1)
    {
        
        
        display_particle(myArray[j]);
    
    }
}




[Edited by - jpetrie on September 12, 2009 12:33:46 PM]
Advertisement
%d is for decimal representation of int, you want %f for doubles.
Ah that was quick. thanks for that.. Im feeling a little stupid right now.
As far as numbers are concerned, printf can only print int and double. Smaller types are implicitly promoted before the function call. (The same is true for every other variadic C function.)
Quote:Original post by DevFred
As far as numbers are concerned, printf can only print int and double. Smaller types are implicitly promoted before the function call. (The same is true for every other variadic C function.)
That's tTechnically true but beware that scanf(...) takes pointers to floats for "%f" arguments, that is unless you use an explicit l or L prefix to use double or long double arguments respectively.

This has bitten me in the ass often enough that I think it's worth mentioning here ;)
Quote:Original post by implicit
Technically true but beware that scanf(...) takes pointers to floats for "%f" arguments

Wow, that's horrible. Good advice.

But since you don't pass a number (but rather a pointer), the rule still holds ;)

This topic is closed to new replies.

Advertisement