Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the length of "char *" array in C?

Tags:

c++

c

I declare the following array:

char* array [2] = { "One", "Two"};

I pass this array to a function. How can I find the length of this array in the function?

like image 984
bubbles Avatar asked Nov 08 '11 01:11

bubbles


People also ask

What is the size of char * in C?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.

How do you find the length of a char array?

first, the char variable is defined in charType and the char array in arr. Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.

Can I use strlen with char * array?

std::size_t strlen( const char* str ); Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character.

What is a char * in C?

C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.


1 Answers

You can't find the length of an array after you pass it to a function without extra effort. You'll need to:

  1. Use a container that stores the size, such as vector (recommended).
  2. Pass the size along with it. This will probably require the least modification to your existing code and be the quickest fix.
  3. Use a sentinel value, like C strings do1. This makes finding the length of the array a linear time operation and if you forget the sentinel value your program will likely crash. This is the worst way to do it for most situations.
  4. Use templating to deduct the size of the array as you pass it. You can read about it here: How does this Array Size Template Work?

1 In case you were wondering, most people regret the fact that C strings work this way.

like image 70
Seth Carnegie Avatar answered Sep 28 '22 03:09

Seth Carnegie