-3

I have a short value and I want to divide it by an integer value. How can I achieve this in C?

short *i;
int divider = 3;
fread(i, sizeof(short), inputfile);
/*write to buffer with i / divider. */
user3712237
  • 173
  • 1
  • 1
  • 8
  • Just typecast the result –  Feb 02 '15 at 00:59
  • Your code has undefined behavior. `i` is a pointer, and you don't initialize it, so it doesn't point to any defined location. `fread` will try to store a `short` value in some undefined memory location. As for the division, what type do you want the result to be, and what do you want to do with it? By "integer", do you mean `int`? `int` and `short` are both integer types. @Isaiah: A cast (not "typecast") is probably not necessary. – Keith Thompson Feb 02 '15 at 01:06
  • @KeithThompson That was just a test code I wrote. I want to read 2 bytes from file into a short, divide the short value by an int and then print the result as a short. Sorry I am new to C. – user3712237 Feb 02 '15 at 01:20
  • That clarification belongs in the question. How is the `short` object allocated? Is there some particular reason you want to do this? – Keith Thompson Feb 02 '15 at 01:30

1 Answers1

0

Perhaps this will help.

short i;
int divider = 3;
fread(&i, sizeof(short), 1, inputfile);

short r = i / divider;

Note that instead of declaring i as a pointer, you declare it as a short type and pass its address to fread. Then just do the divide.

You may also want to check the return value of fread, which indicates how many values were actually read.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61