90

What is a way in C that someone could find the length of a character array?

I will happily accept pseudo-code, but am not averse to someone writing it out if they'd like to :)

phuclv
  • 37,963
  • 15
  • 156
  • 475
not_l33t
  • 1,315
  • 4
  • 15
  • 17
  • You mean other than looking for the NUL? – Ignacio Vazquez-Abrams Nov 15 '10 at 01:44
  • 6
    Either `strlen()`, either `sizeof()`. It depends on what you need. – ruslik Nov 15 '10 at 01:46
  • a string is a specific kind of object stored *in* a Character array (a Character array may not contain a string) –  Nov 15 '10 at 01:50
  • 1
    @pst: The question is sufficiently vague that we can interpret it any way we like. Whether our interpretation is correct depends on what the asker decides to come back with. – Ignacio Vazquez-Abrams Nov 15 '10 at 01:51
  • @pst considering the way the OP put the question, we have the right to assume anything. – ruslik Nov 15 '10 at 01:52
  • ha i love the philosophical comment at the end – not_l33t Nov 15 '10 at 05:13
  • @pst i believe that I asked the wrong question based on a misunderstanding of terminology- still pretty new to this. i read somewhere that C does not actually use strings, but it is probably a mute point considering that i still made a dumb question – not_l33t Nov 15 '10 at 05:17
  • Possible duplicate of [Finding length of char array](http://stackoverflow.com/questions/6150258/finding-length-of-char-array) – JaBe Jun 20 '16 at 08:21

10 Answers10

117

Provided the char array is null terminated,

char chararray[10] = { 0 };
size_t len = strlen(chararray);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 11
    `sizeof()` asnd `strlen()` both return `size_t`, which differs from `int` in that it's potentially larger or smaller and certainly unsigned. – Chris Lutz Nov 15 '10 at 01:55
  • 1
    Note that in the example given, strlen(chararray) returns 0 because the array is empty. – Generic Ratzlaugh Aug 12 '20 at 15:10
  • 1
    please note that strlen will give only the length upto null terminater. For instance is your chararray contatin following entries `chararray[0] = 'a'; chararray[1] = 'b'; chararray[6] = 'c'; chararray[7] = 'd'; ` it will return length as 2 as it finds a null terminater at index 2 – Oshada May 10 '22 at 08:37
41

If you have an array, then you can find the number of elements in the array by dividing the size of the array in bytes by the size of each element in bytes:

char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);

For the specific case of char, since sizeof(char) == 1, sizeof(x) will yield the same result.

If you only have a pointer to an array, then there's no way to find the number of elements in the pointed-to array. You have to keep track of that yourself. For example, given:

char x[10];
char* pointer_to_x = x;

there is no way to tell from just pointer_to_x that it points to an array of 10 elements. You have to keep track of that information yourself.

There are numerous ways to do that: you can either store the number of elements in a variable or you can encode the contents of the array such that you can get its size somehow by analyzing its contents (this is effectively what null-terminated strings do: they place a '\0' character at the end of the string so that you know when the string ends).

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • `sizeof()` asnd `strlen()` both return `size_t`, which differs from `int` in that it's potentially larger or smaller and certainly unsigned. – Chris Lutz Nov 15 '10 at 01:55
  • 1
    This should be the accepted answer. It will return the size of initialized array . – LUser Mar 20 '20 at 18:26
16

Although the earlier answers are OK, here's my contribution.

//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
    //variable used to access the subsequent array elements.
    int offset = 0;
    //variable that counts the number of elements in your array
    int count = 0;

    //While loop that tests whether the end of the array has been reached
    while (*(ptr + offset) != '\0')
    {
        //increment the count variable
        ++count;
        //advance to the next element of the array
        ++offset;
    }
    //return the size of the array
    return count;
}

In your main function, you call the size function by passing the address of the first element of your array.

For example:

char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));
Ross Attrill
  • 2,594
  • 1
  • 22
  • 31
SteveMoros
  • 161
  • 1
  • 2
  • 1
    Why have a separate variable for the offset when you could simply use count? Here's a shorter (but harder to understand) version: `int strlen(const char* pStr){ int i = 0; while (*pStr) { ++i; } return i; }` – DividedByZero May 25 '15 at 15:27
  • char myArray[] = {'h', 'e', 'l', 'l', 'o'}; does not end with '\0' automatically. You need to assign '\0' to myArray manually. myArray[6] = '\0'; at least on my MacOS. g++ 4.2.1, Apple LLVM version 9.1.0 (clang-902.0.39.2) – 1234 Nov 25 '19 at 20:06
  • if you use char myArray[] = "hello"; then your code is working. – 1234 Nov 25 '19 at 20:18
8

You can use strlen

strlen(urarray);

You can code it yourself so you understand how it works

size_t my_strlen(const char *str)
{
  size_t i;

  for (i = 0; str[i]; i++);
  return i;
}

if you want the size of the array then you use sizeof

char urarray[255];
printf("%zu", sizeof(urarray));
Marco
  • 7,007
  • 2
  • 19
  • 49
dco
  • 317
  • 1
  • 13
  • 4
    Any `strlen()` should return `size_t` (which is unsigned) not `int` (which is signed). And the `printf()` specifier for `size_t` is `"%zu"` (or `"%zx"` or `"%zo"` for hex or octal). – Chris Lutz Nov 15 '10 at 02:03
8

If you want the length of the character array use sizeof(array)/sizeof(array[0]), if you want the length of the string use strlen(array).

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
onemasse
  • 6,514
  • 8
  • 32
  • 37
2

There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;
Imre Kiss
  • 21
  • 1
1

using sizeof()

char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5

using string.h

#include <string.h>

char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5

using function (strlen implementation)

int strsize(const char* str);
int main(){
    char h[] = "hello";
    printf("%d\n",strsize(h)); //Output = 5
    return 0;
}
int strsize(const char* str){
    return (*str) ? strsize(++str) + 1 : 0;
}
Beyondo
  • 2,952
  • 1
  • 17
  • 42
1

You can use this function:

int arraySize(char array[])
{
    int cont = 0;
    for (int i = 0; array[i] != 0; i++)
            cont++;
    return cont;
}
slyzion
  • 11
  • 1
0

By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..

Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.

Poni
  • 11,061
  • 25
  • 80
  • 121
0

Well, 11 years later, I run into this issue with a college assignment. The solution I found, worked without having to alter the function signatures that the assignment was asking for.

In my case, I had to make a function that returns the item index if the item existed or depending on if the itemPrefix (e.g. 'B' for Banana) already exists or not in the character array itemPrefixes to avoid passing duplicate prefixes.

So, I had to use a for loop (or while loop). The problem was that the assignment had given me specific signatures for each function and for that specific function it didn't allow me to pass the count variable that was on the main() function as an argument.

I had to improvise.

Both the ways mentioned above didn't work. strlen() didn't work as intended since there was not a '\0' end character that strings have. The sizeof() method also didn't work, because it returned the size of the pointer of the character array that was passed in as an argument instead of the number of elements.

So, this is the function I came up with. A simple while loop that checks whether the current character is NULL (or 0).

void charArrLength(char array[]) {
    int arrLength = 0;
    
    while (array[arrLength] != 0) {
        arrLength++; //increment by 1
    } 
    
    printf("Character array has %d elements", arrLength);
}

For this to work though, in the main() function, you need to declare your character array as a character pointer and then allocate the memory that you need based on the number of items that you ultimately wish to have inside your array.

void charArrLength(char array[]) {
    int arrLength = 0; 
    
    while (array[arrLength] != 0) {
        arrLength++; 
    } 
    
    printf("Character array has %d elements", arrLength); //should give 33
} 

int main() { 
    char *array; //declare array as a pointer
    int arraySize = 33; //can be anything 
    
    array = (char*) malloc(arraySize * sizeof(char)); 
    
    charArrLength(array);

    free(array); //free the previously allocated memory
}

Below you will see how I utilised this function in my assignment.

First, here is the above function tailored to my needs.

int isItemExists(char itemPrefixes[], char itemPrefix) {
    int count = 0; //declare count variable and set to 0
    int itemIndex = -1; //declare item index variable and set it to -1 as default

    while (itemPrefixes[count] != 0) {
        count++;
    }

    for (int i = 0; i < count; i++) {
        if (itemPrefix == itemPrefixes[i]) {
            itemIndex = i; //if item exists, set item index to i
        }
    }

    return itemIndex;
}

Then, how I declared the itemPrefixes array in main() function and how I allocated the needed memory based on n (the number of items the user would like to add to itemPrefixes array).

char *itemPrefixes;
    
int n = 0; //number of items to be added variable

printf("> Enter how many items to add: ");
scanf("%d", &n);

//allocate n * size of char data type bytes of memory
itemPrefixes = (char*) malloc(n * sizeof(char));

And finally, here is how that function was used after all.

do {
    printf("\n\n> Enter prefix for item %d: ", i + 1);
    scanf(" %c", &itemPrefix);
    
    //prompt the user if that itemPrefix already exists
    if (isItemExists(itemPrefixes, itemPrefix) != -1) {
        printf("\nItem prefix already exists! Try another one.\n");
    }
} while (isItemExists(itemPrefixes, itemPrefix) != -1);

Also, in the end of the code I free the previously allocated memory.

free(itemPrefixes);

To clear this out, again, this could be much easier if the conditions were different. The assignment was strict about not passing n as an argument. Nevertheless, I hope I help someone else that might be looking for this in the future!

Just for the sake of it, if anybody sees this and has something simpler to suggest, feel free to tell me.

konmaris
  • 1
  • 2