Answer: Let’s learn this by considering an example, and analysing it’s output when program is run on Linux System.
/* * sizeof_vs_strlen.c -- program shows difference between using sizeof and * strlen with array and string */ #include <stdio.h> #include <string.h> int main(void) { char msg[] = {'c','h','r','i','s','t','o','p','h','e','r'}; /* Character array */ char name1[] = "christopher"; /* character array */ char *name2 = "christopher"; /* string literal */ printf("sizeof: size of char array msg[] \"%s\" is %d bytes!\n", msg, sizeof(msg)); printf("strlen: size of char array msg[] \"%s\" is %d bytes!\n", msg, strlen(msg)); printf("sizeof: size of char array name1[] \"%s\" is %d bytes!\n", name1, sizeof(name1)); printf("strlen: size of char array name1[] \"%s\" is %d bytes!\n", name1, strlen(name1)); printf("sizeof: size of string \"%s\" is %d bytes!\n", name2, sizeof(name2)); printf("strlen: size of string \"%s\" is %d bytes!\n", name2, strlen(name2)); return 0; }
Output follows:
sizeof: size of char array msg[] "christopher" is 11 bytes! strlen: size of char array msg[] "christopher" is 11 bytes! sizeof: size of char array name1[] "christopher" is 12 bytes! strlen: size of char array name1[] "christopher" is 11 bytes! sizeof: size of string "christopher" is 8 bytes! strlen: size of string "christopher" is 11 bytes!
Notice that sizeof operator returns actual amount of memory allocated to the array including NULL byte if it’s included in initializer’s list or without it if it’s not there. Basically, sizeof operator is used to evaluate amount of memory, in bytes, allocated to its argument.
sizeof(arg); /* 'arg' can be any data or type */
In case of name2, which is a pointer to string “christopher”, sizeof returns size of pointer which is 8 bytes on Linux, although strlen() returned actual no. of characters in the string without counting NULL byte.
Remember that strlen() function primarily a string handling function used with strings and always returns actual no. of characters in the string without counting on NULL byte. We’ll see more about various string handling functions later.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Apply for C Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Check Computer Science Books