Strings as paramaters
The string can be passed to a function just as in a normal array. The following examples are used for printing the number of characters in the string:
#include<stdio.h> int main ( ) { char s1[6] = "abcde "; int cnt = 0; cnt = cnt_str(s1); // A printf( " total characters are %d \n", cnt); getchar(); return 0; } int cnt_str(char s1[]) // B { int cn = 0; while( (cn < 6) && (s1[cn]!= '\0')) cn++; return(cn); }
Explanation
- A function, cnt_str, calculates the number of characters in a string. The string is passed just as a character array. When the array is passed, the base address of the array is actually what gets passed.
- Statement B is called to a function in which s1 is passed just as a normal array.