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?
CodePudding user response:
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: