DoctorCloud DoctorCloud - 5 months ago 25
C Question

Adding pointers to an old program

I've got a program that converts a number into different fictional currencies, originally this program didn't have any functions other than main and as such contained no pointers. I understand why pointers are used, but I don't understand how they are actually implemented in code... I'm supposed to use a conversion function to handle all the work and only have my main function handle the output. This is what I have so far, where do pointers come into play?

#include <stdio.h>
#include <stdlib.h>

void convert(int total_knuts, int *galleons, int *sickles, int *knuts)
scanf("%d", &knuts); //user inputs first currency
if (total_knuts >= 0 && knuts <= 1000000000){
int galleons = (knuts / 29)/17;
int sickles = (knuts / 29)%17;
int *knuts = (knuts%29);
} else {
printf("Invalid!"); //prints if user does not enter an appropriate integer

int main()
printf("%d galleons\n", galleons); //shows galleon currency value
printf("%d sickles\n", sickles); //shows sickle currency value
printf("remaining knuts %d", &remainder); //shows remaining knuts

return 0;

Answer Source

Pointers are used to store addresses of variables.

In your case you probably want to declare all the currency variables in main and then pass the addresses of these variables to convert, which can then store the calculated values at these addresses.

After the convert function call, the calculated values are the available in main.

Working code:

#include <stdio.h>

void convert (unsigned int total_knuts, unsigned int *galleons, unsigned int *sickles, unsigned int *knuts) {
    *galleons = total_knuts / (29 * 17);
    total_knuts = total_knuts % (29 * 17);

    *sickles = total_knuts /  17;
    total_knuts = total_knuts % 17;

    *knuts = total_knuts;

int main () {
    unsigned int total_knuts;
    unsigned int galleons;
    unsigned int sickles;
    unsigned int knuts;

    printf ("Knuts: ");
    scanf ("%u", &total_knuts); // user inputs total knuts
    convert (total_knuts, &galleons, &sickles, &knuts);

    printf ("%u galleons\n", galleons); // shows galleon currency value
    printf ("%u sickles\n", sickles); // shows sickle currency value
    printf ("remaining knuts %u\n", knuts); // shows remaining knuts

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download