1

I learn C++, pointers/references, some basic stuff. I made a little program that calculate difference between two times. My program works fine, but i have no idea why it returns a big value like 123123123:53442344 at the end when there are a & signs before variables. There`s a code of my program

#include <iostream> 
#include <stdio.h>

int main() {
    int userHour, userMinutes;

    printf_s("Enter first hour: ");
    scanf_s("%d:%d", &userHour, &userMinutes);

    int difference = userHour * 60 + userMinutes;

    printf_s("Enter second hour: ");
    scanf_s("%d:%d", &userHour, &userMinutes);

    difference = abs(difference - (userHour * 60 + userMinutes));
    userHour = difference / 60;
    userMinutes = difference % 60;

    printf("Difference is %02d:%02dh", &userHour, &userMinutes);
}

The problem is in the last line of code, i couldn't find an answer in a debugger or Google (inb4 i'm pretty new in programming, show me how to look for answers :( )

Clifford
  • 88,407
  • 13
  • 85
  • 165
oreze
  • 11
  • 2
  • C or C++? They're different languages; please pick one. – Jonathon Reinhart Oct 20 '19 at 15:28
  • I have removed the C tag since it is not valid C, though the things that make it "not C" are irrelevant to the code. It is not at all clear why `` is included. Note that in C++ a "reference" is a specific thing distinct from a pointer - this code does not use references. – Clifford Oct 20 '19 at 15:32
  • 1
    Using `printf` with `%02d` expects an `int`, not an address to an `int`. – Eljay Oct 20 '19 at 15:32
  • 1
    Don't confuse `scanf` with `printf` for input you need somewhere to write the values, for output you just need the values - not their addresses. – Clifford Oct 20 '19 at 15:35
  • If you are learning C++, you should be using `std::cout <<` and `std::cin >>` for output and input, not the C library functions like `printf`. You are also mixing different variants of the IO functions, which work different (e.g. `printf` vs `printf_s`). It is unclear why you are mixing these. You need a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to teach you the language. Throwing random stuff together does not work in C++. – walnut Oct 20 '19 at 15:52

1 Answers1

1

&userHour means give me a pointer to the memory address of userHour. Thus printf will print the value of that memory address. (Note, not the value stored in memory at that address, the numerical value of the memory address itself.)

You want printf("Difference is %02d:%02dh", userHour, userMinutes);.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43