0

I have a structure defined in quaternions.c

typedef struct quaternion{
        double arr[4];
} quaternion;

with header file

#ifndef QUATERNIONS_H
#define QUATERNIONS_H

typedef struct quaternion{
        double arr[4];
} quaternion;

#endif

Since this is my first time using C structures, I tried testing it out.

#include <stdio.h>
#include "quaternions.h"
        
int main(){
        quaternion a;
        a.arr[1]=2.5;
        printf("%d\n",a.arr[1]);
        return 0;
}

As far as I can tell, what I'm doing is almost identical to this article. However, when I compile and run this, it prints a random gibberish number. What am I doing wrong?

Leon
  • 75
  • 5
  • 4
    Tangential to your immediate problem, note that `quaternions.c` should `#include "quaternions.h"` rather than write the definition out a second time. The header will eventually declare functions, and those function declarations must be checked against the definitions and against the uses of those functions. The header is the glue that allows this to be cross-checked by the compiler. – Jonathan Leffler Jun 24 '22 at 01:48
  • Please check print type format. If you want to print double variable type, you must use '&f' not '%d'. – linuxias Jun 24 '22 at 03:54
  • Thanks, @JonathanLeffler. Like I said, this is my first time using structs, so I wasn't sure how to go about formatting the header. – Leon Jun 24 '22 at 04:20
  • @linuxias: You probably mean `%f` instead of `&f`. – Andreas Wenzel Jun 24 '22 at 08:35

1 Answers1

3

The correct printf conversion format specifier for a double is %f, not %d. See the documentation for that function for further information.

You should change the line

printf("%d\n",a.arr[1]);

to:

printf("%f\n",a.arr[1]);

By using the wrong conversion format specifier, your program is invoking undefined behavior. This explains why your program is printing "random gibberish" instead of the desired output.

Most good compilers will warn you if you use the wrong conversion format specifier. If your compiler doesn't warn you, then I suggest that you make sure that you have all warnings enabled. See this question for further information:

Why should I always enable compiler warnings?

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Ah, of course. What a silly mistake. Thanks for the information about compiler warnings. My compiler didn't give me one. – Leon Jun 24 '22 at 04:18