CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Functions with pointer parameters

We know that pointers are simply variables.
We now use this fact to implement functions that receive pointers as parameters.

A pointer parameter will be initialized with an address when the function is called.

Consider two equivalent implementations of C's standard strlen function - the traditional approach is to employ a parameter that "looks like" an array; new approaches employ a pointer parameter:

int strlen_array( char array[] )
{
    int   len = 0;

    while( array[len] != '\0' ) {
        ++len;
    }

    return len;
}


int strlen_pointer( char *strp )    
{
    int   len = 0;

    while( *strp != '\0' ) {
        ++len;
        ++strp;
    }
    return len;
}


int strlen_pointer( char *strp )    
{
    char   *s = strp;

    while( *s != '\0' ) {
        ++s;
    }
    return (s - strp);
}

During the execution of the function, any changes to the pointer will simply change what it points to.
In this example, strp traverses the null-byte terminated character array (a string) that was passed as an argument to the function.

We are not modifying the string that the pointer points to, we are simply accessing adjacent, contiguous, memory locations until we find the null-byte.

 


CITS2002 Systems Programming, Lecture 11, p10, 26th August 2024.