0

I'm starting to learn pointers in C. But there's something strange that I cannot understand in this code.

#include <stdio.h>

int* max(int* a, int* b);

int main(int argc, char const* argv[]) {
  int a = 7, b = 10, *m;
  m = max(&a, &b);
  printf("%d", m);
  return 0;
}

int* max(int* a, int* b) {
  if (*a > *b) return a;
}

In the function max I compared *a and *b and return a if *a > *b, but I return nothing when *a < *b. However, it printed 10, which is the value of *b. If I change the value of b to 7 in main function, it printed 7. If I use *m than m, it said segmentation fault, but when using m instead of *m, it works well. I cannot understand it!! Hope somene can help me!

Dexter
  • 1
  • This is called Undefined Behaviour in C. Code with UB in it will have unpredictable results. It can crash, it can produces wrong values, it can even appear to "work" or any other behaviour. And the behaviour can change at any time. – kaylum Oct 22 '22 at 07:14
  • Are you getting a compiler warning about `max` not always returning a value? If not, enable warnings (`-Wall -Wextra -pedantic` for *gcc* and *clang*). Then fix `max` so that it always returns something. – hyde Oct 22 '22 at 07:14
  • change to `print("%d", *m);` – Xin Cheng Oct 22 '22 at 07:18

0 Answers0