notes-sizeof-strlen

migrate from https://cmakerhk.wordpress.com/2018/09/28/sizeof-vs-strlen/


Sizeof()

#include
int main()
{
printf("%d\n",sizeof(char)); // output 1
printf("%d\n",sizeof(int)); // output 4
printf("%d\n",sizeof(float));// output 4
printf("%d", sizeof(double));// output 8
return 0;
}
Sizeof will return the size of the variable
#include
int main()
{
int arr[] = {1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14};
printf("Number of elements :%d", sizeof(arr)/sizeof(arr[0]));
return 0;
}
Number of elements :11
This is useful for getting the number of the elements of an array.

allocate memory dynamically - To allocate block of memory dynamically.

int *ptr = malloc(10*sizeof(int));
strlen()
size_t strlen(const char *str)
not include \0

//========compare

Since strlen() not inlclude \0

// C program to demonstrate difference
// between strlen() and sizeof()
#include
#include
int main()
{
char str[] = "November";
printf("Length of String is %d\n", strlen(str)); //8
printf("Size of String is %d\n", sizeof(str)); //9
}
#include
#include
using namespace std;
int main()
{
char a[] = {"Geeks for"};
char b[] = {'G','e','e','k','s',' ','f','o','r'}; //9 char total
cout << "sizeof(a) = " << sizeof(a);
cout << "\nstrlen(a) = "<< strlen(a);
cout<< "\nsizeof(b) = " << sizeof(b);
cout<< "\nstrlen(b) = " << strlen(b);
return 0;
}
sizeof(a): 10 //include the NULL at the end

strlen(a): 9 // not include the NULL

sizeof(b): 9 // total 9 char ma

strlen(b):11 // abnormal

ref:

https://www.geeksforgeeks.org/sizeof-operator-c/

https://www.tutorialspoint.com/c_standard_library/c_function_strlen.htm

https://www.geeksforgeeks.org/difference-strlen-sizeof-string-c-reviewed/