JakobVinkas
JakobVinkas

Reputation: 1063

Changing global c variable inside a struct array

I have a case where I have defined a global struct array in a seperate header file that I want to be able to change from function in another file but I can not make it work, I believe that the problem can be simplified to the follwing:

#include <stdio.h>

struct point{
    /*
    Measured points and reflector coordinates, both true and estimated
    are stored as points.
    */
    float x;    // x-coordinate [mm]
    float y;    // y-coordinate [mm]
} coordinates[3];


void set_value(){
    coordinates[0].x = 10.0;
    coordinates[1].x = 11.0;
    coordinates[2].x = 12.0;
}

int main(int argc, char const *argv[])
{
    set_value();
    printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

}

Which gives the following non-sensical output:

[0]: 0, [1]: 1076101120, [2]: 0

The output that I want is the follwoing:

[0]: 10.0, [1]: 11.0, [2]: 12.0

What am I doing wrong?


Edit: It was just me forgetting to change %d to %f while testing out different struct types.

Upvotes: 0

Views: 46

Answers (2)

Shilpa S Jadhav
Shilpa S Jadhav

Reputation: 59

To get required output replace your printf in main()

from

printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

To

printf("[0]: %.1f, [1]: %.1f, [2]: %.1f", coordinates[0].x, coordinates[1].x, coordinates[2].x);

Upvotes: 0

tdao
tdao

Reputation: 17668

printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

You used wrong control format for printf, it should be %f instead for floating variables:

printf("[0]: %f, [1]: %f, [2]: %f", coordinates[0].x, coordinates[1].x, coordinates[2].x);

Upvotes: 1

Related Questions