// A Demo file to look at how variables, arrays and functions interact
// Marc Chee, April 2019

#include <stdio.h>

int doubler(int number);
void doublePointer(int *number);
void doubleAll(int length, int numbers[]);

int main (void) {
    int x = 5;
    int y = doubler(x);
    printf("x is %d and y is %d.\n", x, y);
    // "x is 5 and y is 10"
    // This is because the doubler function takes the value 5 from x
    // and copies it into the variable "number" which is a new variable
    // that only lasts as long as the doubler function runs
    
    int *pointerX = &x;
    doublePointer(pointerX);
    printf("x is %d.\n", x);
    // "x is 10"
    // This is because doublePointer gets given access to x via its
    // copied pointer . . . since it changes what's at the other end of
    // that pointer, it affects x
    
    int myNums[3] = {1,2,3};
    doubleAll(3, myNums);
    printf("Array is: ");
    int i = 0;
    while(i < 3) {
        printf("%d ", myNums[i]);
        i++;
    }
    printf("\n");
    // "Array is 2 4 6"
    // Since passing an array to a function will pass the address
    // of the array, any changes made in the function will be made
    // to the original array
}

// return a value that's double the value we're given 
int doubler(int number) {
    number = number * 2;
    return number;
}

// Double the value of the variable the pointer is aiming at
void doublePointer(int *numPointer) {
    *numPointer = *numPointer * 2;
}

// Double all the elements of a given array
void doubleAll(int length, int numbers[]) {
    int i = 0;
    while(i < length) {
        numbers[i] = numbers[i] * 2;
        i++;
    }
}

Resource created Tuesday 09 April 2019, 12:27:26 AM.

file: functions.c


Back to top

COMP1511 19T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G