Arrays as Arguments to Functions

Passing an argument to a function becomes more complicated when the argument is an array.  When we pass an array as an argument, the argument does not receive the contents of the array. Instead, the address of the initial element of the array is passed.

#include <stdio.h>
#define ARRAYSIZE 5

void printArray(int array[]);

int main(void){
    
    int array[ARRAYSIZE] = {3, 9, 27, 81, 243};
    
    printArray(array);
    
    return 0;
    
}

void printArray(int array[]){
    int i = 0;
    while(i < ARRAYSIZE){
        printf("element %d = %d\n", i, array[i]);
        i++;
    }
}

The value of strings lies in the fact that a string, which is really a char array, has a terminating character. Therefore, we do not need to pass the length of the array to a called function.

#include <stdio.h>

int stringLength(char s[]);

int main(void){
    char string1[]="Is that a real poncho or a Sear's poncho?";
    char string2[]="You are technically correct - the best kind of correct.";
    
    printf("%s has %d characters\n",
            string1, stringLength(string1));
    
    printf("%s has %d characters\n", string2, stringLength(string2));
    
    return 0;
}


int stringLength(char s[]){
    int i = 0;
    
    /*
     * search for terminating null
     */
    for(i; s[i]!='';i++){;}
    
    /*
     * i is now the lenth of the string
     */
    return i;
    
}

The crucial point is to not think of the parameter inside the called function as an array of characters, but as a variable that holds the address of the initial element in the array. The technical term for such a variable is a character pointer.

#include <stdio.h>

#define STRLENGTH 100
void stringCopy(char *targString, char *srcString);

int main(void){

    char string1[STRLENGTH] = "I solemnly swear that I am up to no good.";
    char string2[STRLENGTH];
    
    stringCopy(string2, string1);
    
    printf("%s\n", string2);
    printf("%s\n", string1);
    return 0;
    
}

void stringCopy(char *targString, char *srcString){
    
    while(*srcString){
        /*
         * parentheses in expression below
         * not actually necessary, but...
         */
        *(targString++) = *(srcString++);
    }
    *targString = '';
}

The stringCopy() function above copies the characters from one char array to another.

Interested in learning C? Take a look at my book, that contains over 200 all-new sample programs: http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/