Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of a const char pointer

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......

like image 374
Atinuke Avatar asked Feb 09 '17 04:02

Atinuke


People also ask

What is the size of a char pointer?

sizeof(char *) is the size of the pointer, so normally 4 for 32-bit machine, and 8 for 64-bit machine.

How many bytes is a const char?

sizeof(char) is 1. Not because a char has one byte (8 bits), but because that's what the standard defines.

How do you find the length of a const character in C++?

Using C library function strlen() method: The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.


1 Answers

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
like image 174
chux - Reinstate Monica Avatar answered Nov 01 '22 09:11

chux - Reinstate Monica