Skip to main content

Section 27.8 Function to Print a Number

So far we have only printed a 3-digit number by dereferencing successively the pointers to the three digits. This is not something that could be generalized to an arbitrarily long number and that’s why next our goal is to print an arbitrary number using a function to which we only pass a pointer to the first digit of the number.

Activity 27.5.

Let’s move the printing of our number into a function. The function should work for arbitrarily long numbers, not just for our 3-digit number. Please write a function printNumber() to which you pass a pointer to the first digit of your number and which prints all of the digits of the number to the screen. The function does not need to return anything.

Compile and run the code below in your own C environment.

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

struct digit {
    int num;
    struct digit *next;
};

typedef struct digit digit_t;

digit_t *createDigit(int);
void append(digit_t * start, digit_t * newDigptr);

int main(void) {
    digit_t *start, *newDigptr, *tmp;
    start = createDigit(5);
    newDigptr = createDigit(3);
    append(start, newDigptr);
    newDigptr = createDigit(7);
    append(start, newDigptr);

/* print the number */
    printf("We are storing the number %d%d%d.\n", start->num, start->next->num, start->next->next->num);
    
/* free all allocted space */
    tmp = start->next;
    free(start);
    start = tmp;
    tmp = start->next;
    free(start);
    free(tmp);
    return 0;
}

digit_t *createDigit(int dig) {
    digit_t *ptr;
    ptr = (digit_t *) malloc(sizeof(digit_t));
    ptr->num = dig;
    ptr->next = NULL;
    return(ptr);
}

void append(digit_t * start, digit_t * newDigptr) {
    digit_t *end = start;
    while(end->next != NULL) {
        end = end->next;
    }
    end->next = newDigptr;
}