Basic C program to calculate string length.
#include <stdio.h>
/**
* Method to calculate string length.
* Returns -1 in case of null pointer, else return string length.
**/
int length(char *str) {
int i = -1;
// Check for NULL pointer, then return i = -1;
if(str == NULL) return i;
// Iterate till the empty character.
while (str[++i] != '\0');
return i; // Return string length.
}
int main (int argc, char **argv) {
int len = 0;
char abc[] = "hello";
len = length(abc);
printf("%d", len);
return 0;
}
NOTE: For better way, we should always pass the array size to function to avoid the case of out of bound access. For example the prototype of method should be:
/**
* @desc calculate the length of str.
* @param1 *str pointer to base address of char array.
* @param2 size = capacity of str to hold characters.
* @return int -1 in case of NULL, else return string length.
**/
int length (char *str, int size);