开发者

Finding the length of a Character Array in C

What is a way in C that someone could find the length of a开发者_如何学JAVA character array?

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


Provided the char array is null terminated,

char chararray[10] = { 0 };
size_t len = strlen(chararray);


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


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]));


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));


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


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++;


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;
}


You can use this function:

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜