0

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.

2
  • use %f instead of %d inside printf Commented Aug 25, 2020 at 6:52
  • Maybe ask your compiler to warn you about such mistakes by turning on all warnings and minding them helps in the future. Commented Aug 25, 2020 at 7:49

2 Answers 2

1
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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.