Difference between strlen() and sizeof() in C

Difference between strlen() and sizeof() in C

5 mins read1.8K Views Comment
Updated on Mar 29, 2023 17:32 IST

In this tutorial, we will discuss two commonly used functions in the C programming language – strlen() and sizeof(). Both functions deal with determining the size of objects in memory, but they do so in different ways and can be used for different purposes.

2023_03_Feature-Image-Templates-6.jpg

We will learn the differences between these two functions, with examples to illustrate how they can be used in different situations. We will be covering the following sections: 

Difference between strlen() and sizeof() in C 

Here is a comparison table that highlights the main differences between strlen() and sizeof() functions in C: 

 Benchmark strlen()  sizeof() 
Purpose  Determines the length of a string (excluding null character)  Determines the size in bytes of a variable or data type 
Parameter  A string  A variable or data type 
Return value  The length of the string  The size in bytes of the variable or data type 
Null terminator  Excludes the null terminator from the length calculation  Includes the null terminator in the size calculation 
Applicable types  Only applicable to strings  Applicable to any variable or data type 
Example usage  char str[] = “Hello, World!”;<br>int len = strlen(str);  int arr[] = {1, 2, 3, 4, 5};<br>int size = sizeof(arr); 

The strlen() function is used to determine the length of a string (excluding the null terminator). In contrast, the sizeof() function is used to determine the size in bytes of a variable or data type (including the null terminator for strings). 

You can also explore: Difference Between Array and Structure in C

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4.24 K
6 weeks
475
6 weeks
– / –
45 hours
4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
4 K
80 hours

What is strlen() in C? 

In C programming language, strlen() is a standard library function that is used to determine the length of a string. The strlen() function takes a null-terminated string as input and returns the number of characters in the string, excluding the terminating null character. 

The syntax of strlen() function in C is: 

size_t strlen(const char *str); 

Here, str is the null-terminated string whose length needs to be determined, and size_t is an unsigned integer type defined in the C standard library that is used to represent sizes and indices. 

The strlen() function scans the input string from the beginning until it reaches the null character ‘\0‘ that marks the end of the string. It returns the number of characters in the string before the null character. 

You can also explore: Stored procedure Vs. Function: What are the differences?

Example Usage of strlen() 

Here are some examples of using the strlen() function in C: 

Example 1: Finding the length of a string 


 
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
Copy code

Output: 

2023_03_image-67.jpg

In this example, we first declare a character array str and initialize it with a string “Hello, World!”. Then, we use the strlen() function to find the length of the string and store it in the variable len. Finally, we print the length of the string using printf() function. 

Example 2: Trimming a string 


 
#include <stdio.h>
#include <string.h>
void trim_string(char* str) {
int len = strlen(str);
int start = 0, end = len - 1;
// Trim leading spaces
while (str[start] == ' ') {
start++;
}
// Trim trailing spaces
while (str[end] == ' ') {
end--;
}
// Add null terminator to end of trimmed string
str[end+1] = '\0';
// Shift trimmed string to beginning of original string
str = str + start;
printf("Trimmed string: %s\n", str);
}
int main() {
char str[] = " Hello, World! ";
printf("Original string: %s\n", str);
trim_string(str);
return 0;
}
Copy code

Output: 

2023_03_image-68.jpg

As you can see, the trim_string() function has successfully trimmed the leading and trailing spaces from the original string using the strlen() function to determine the length of the string. 

What is sizeof() in C? 

In C, sizeof() is a built-in operator that is used to determine the size, in bytes, of a variable or data type.  

The syntax of the sizeof() operator is as follows: 

sizeof(expression) 

Here, the expression can be a variable, data type, or any other expression. The sizeof() operator returns the size of the object represented by the expression in bytes. 

For example, if we want to find the size of an integer variable x, we can use the sizeof() operator as follows: 


 
int x;
printf("Size of integer variable x is: %lu bytes", sizeof(x));
Copy code

This will print the size of the integer variable x in bytes. 

It’s important to note that the size of a data type can vary depending on the implementation and the system on which the program is running. The sizeof() operator is a compile-time operator and the result is determined at the time of compilation. 

You can also explore: Difference between Malloc and Calloc

Example Usage of sizeof() 

Here are some examples of using the sizeof() function in C: 

Example 1: Finding the size of a variable  


 
#include <stdio.h>
int main() {
int num = 123;
double dbl = 3.14;
printf("Size of num variable: %ld bytes\n", sizeof(num));
printf("Size of dbl variable: %ld bytes\n", sizeof(dbl));
return 0;
}
Copy code

Output: 

2023_03_image-69.jpg

In this example, we declare an integer variable num and a double variable dbl. We use the sizeof() function to determine the size of each variable in bytes, and print the results using printf() function.  

Example 2: Finding the size of an array  


 
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
printf("Size of arr array: %ld bytes\n", sizeof(arr));
printf("Number of elements in arr array: %d\n", len);
return 0;
}
Copy code

Output: 

2023_03_image-69.jpg

In this example, we declare an integer array arr with 5 elements. We use the sizeof() function to determine the size of the entire array in bytes, and divide it by the size of each element to get the number of elements in the array. We print both the size of the array and the number of elements in the array using printf() function. 

Example 3: Dynamically allocating memory using sizeof() 


 
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size, i;
// ask user for size of array
printf("Enter size of array: ");
scanf("%d", &size);
// allocate memory dynamically using size
arr = (int*) malloc(size * sizeof(int));
// fill array with values from 0 to size-1
for (i = 0; i < size; i++) {
arr[i] = i;
}
// print array
printf("Array contents: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// free dynamically allocated memory
free(arr);
return 0;
}
Copy code

Output: 

2023_03_image-71.jpg

In this program, we declare a pointer arr that will point to the dynamically allocated memory. We also declare a variable size to hold the size of the array that the user will input. 

After getting the size from the user, we dynamically allocate memory using malloc(). The size * sizeof(int) expression calculates the total amount of memory that needs to be allocated for the array. We cast the return value of malloc() to an int pointer so that it matches the type of arr

We then fill the array with values from 0 to size-1, and print the contents of the array. 

Finally, we free the dynamically allocated memory using free(). This is important to prevent memory leaks. 

You can also explore: Difference Between C and C++

Endnotes 

Hope this article was helpful for you to understand the key differences between strlen() and sizeof() functions in C. If you want to learn more about C programming and solidify your basics, you can explore our articles on C. 

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio