Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between strlen() and sizeof() for string in C
In C programming, strlen() and sizeof() are commonly used to work with strings, but they serve different purposes and return different values. Understanding their differences is crucial for effective string manipulation.
strlen() Function
The strlen() function is declared in string.h header file and calculates the actual length of a string by counting characters until it encounters the null terminator '\0'.
Syntax
size_t strlen(const char *string);
string − The string whose length is to be calculated.
Example
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "Hello";
int len = strlen(s1);
printf("Length of string s1: %d
", len);
printf("Memory allocated for s1: %lu bytes
", sizeof(s1));
return 0;
}
Length of string s1: 5 Memory allocated for s1: 10 bytes
sizeof() Operator
The sizeof() operator returns the total memory allocated for a variable or data type in bytes. It is a compile-time operator that calculates size based on the declaration, not the actual content.
Syntax
sizeof(type); sizeof(variable);
Example
#include <stdio.h>
int main() {
int a = 16;
printf("Size of variable a: %lu
", sizeof(a));
printf("Size of int data type: %lu
", sizeof(int));
printf("Size of char data type: %lu
", sizeof(char));
printf("Size of float data type: %lu
", sizeof(float));
printf("Size of double data type: %lu
", sizeof(double));
return 0;
}
Size of variable a: 4 Size of int data type: 4 Size of char data type: 1 Size of float data type: 4 Size of double data type: 8
Key Differences
| Aspect | strlen() | sizeof() |
|---|---|---|
| Purpose | Counts actual characters in string | Returns allocated memory size |
| Runtime | Runtime calculation | Compile-time calculation |
| Header Required | string.h | None (built-in operator) |
| Null Terminator | Stops at '\0' | Includes all allocated bytes |
Practical Comparison Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Programming";
char str2[] = "C Language";
printf("str1 = "%s"
", str1);
printf("strlen(str1) = %lu
", strlen(str1));
printf("sizeof(str1) = %lu
", sizeof(str1));
printf("str2 = "%s"
", str2);
printf("strlen(str2) = %lu
", strlen(str2));
printf("sizeof(str2) = %lu
", sizeof(str2));
return 0;
}
str1 = "Programming" strlen(str1) = 11 sizeof(str1) = 20 str2 = "C Language" strlen(str2) = 10 sizeof(str2) = 11
Conclusion
Use strlen() when you need the actual string length for processing, and sizeof() when you need to know the memory allocation size. Understanding this difference prevents common programming errors and helps optimize memory usage.
