#include<stdio.h>
int main() {
char *arr[] = { "sunbeam ","dac","wimc","pune","karad" };
char **ptr;
int i;
printf("size : %d\n",sizeof(arr));
}
this c program showing 40 as output please explain me how it comes.
#include<stdio.h>
int main() {
char *arr[] = { "sunbeam ","dac","wimc","pune","karad" };
char **ptr;
int i;
printf("size : %d\n",sizeof(arr));
}
this c program showing 40 as output please explain me how it comes.
Two things: arr
is an array of pointers, and sizeof
returns the size in bytes.
Since arr
is an array of five pointers to char
, the result of sizeof(arr)
is equal to 5 * sizeof(char *)
. Which on a typical 64-bit system (where pointers are 64 bits, i.e. 8 bytes) is 40
bytes.
Furthermore, you use the wrong format to print the result of sizeof
. You should be using "%zu"
(the z
modifier because the argument is a size_t
, the u
type because it's unsigned). See e.g. this printf
(and family) reference for more information.
Pointers will be size 2 on a 16-bit system, 4 on a 32-bit system, and 8 on a 64-bit system.
Your code(Simplified for explanation) :
#include <stdio.h>
int main() {
char*arr[] = { "a","b","c","d","e" };
char *arr1;
char **arr2;
printf("Size of Array : %zu \n", sizeof(arr) );
printf("Size of Array1 : %zu \n",sizeof(arr));
printf("Size of Array2 : %zu \n",sizeof(arr));
return 0;
}
Output:
main
Size of Array : 40
Size of Array1 : 8
Size of Array2 : 8
Your program has nothing to do with the values inside array
char *arr[] = { "a","the largest string in the array will still take 8 bytes","c","d","e" };
the pointer to array is a pointer to all those values, takes 8 bytes for each index in 64 architecture. sizeof(arr)
thus returns 40bytes for 5 elements .