How to get the size of a const char pointer
13,993
Solution 1
To get the size of a const char
pointer:`
printf("%zu\n", sizeof(const char *));
To get the size of the array array[]
:
const char *array[] = {"ax","bo","cf"};
printf("%zu\n", sizeof array);
To get the number of elements in the array array[]
, divide the size of the array by the size of an array element.
const char *array[] = {"ax","bo","cf"};
// Size of array/size of array element
printf("%zu\n", sizeof array / sizeof array[0]);
// expect 3
Solution 2
anyType array[3] = {};
sizeof(array[0]) //will return the size of one element of any array
sizeof(array) //will return the storage requirement of the entire array
(sizeof(array)/sizeof(array[0])) //will return the number of elements in the array
But remember that sizeof() resolves at compile time so it only works if you have the actual array variable, not a pointer to an element. Meaning you can't pass the array into a function and then take the sizeof() of the passed parameter unless you declare the parameter to be an array of fixed size.
Solution 3
you need to first find out the size of const char *
then you need to divided by this to size of you array like this :
#include <stdio.h>
#include<string.h>
int main()
{
const char *array[] = {"ax","bo","cf"};
printf("%d",sizeof(array)/sizeof(const char*));
return 0;
}
Author by
Atinuke
Updated on June 04, 2022Comments
-
Atinuke almost 2 years
const char *array[] = {"ax","bo","cf"};
tried
printf("size of array = %lu\n", sizeof(const char*)); result != 3
also
printf("size of array = %lu\n", sizeof(array)); result != **DESIRED ANSWER** = 4
NOTE... I have read related questions on here but none had a relation with my question......
-
RoadRunner about 7 yearsJust out of curiosity, which is clearer?
sizeof array / sizeof array[0]
orsizeof array / sizeof *array
. BTW I think the third example has typo. Should bearray
instead ofa
. -
chux - Reinstate Monica about 7 years@RoadRunner Which is best
sizeof array / sizeof array[0]
orsizeof array / sizeof *array
is easy. Every group should employ a coding style that settles style issues like this and then use the agreed upon one. I prefer[]
at it emphasizes the array nature of the object. -
chux - Reinstate Monica about 7 years@RoadRunner I avoid the
sizeof array/sizeof(const char*)
style as that is harder to code, review and maintain. To know the type is correct requires cross checking with the declaration. This is especial a nuisance when the type is defined in a field of some structure located in a header file. -
chux - Reinstate Monica over 3 years"sizeof() resolves at compile time " -->
sizeof
also applies to variable length arrays, a run-time determination. -
bd2357 over 3 yearsGood point on variable arrays, There is also the issue of an expression with side effects as parameter to sizeof which must be evaluated. But this is such a bad practice I don't think I have ever seen it in the wild.