1

Given an array of character strings such as...

char *example[] = {"s", "ss", "sss"};

How can I write a function to count the total number of chars in the array including the terminating characters, without using the standard library for strlen() etc.

Follows is my attempt

int countChars(char *array[], int len)
{
    int total = 0, count = 0;


    for (int i = 0; i < len; i++)
    {
        if (array[i] != NULL)
        {
            while (*array[i] != '\0') {
                count++;
            }
            count++;
        }
        total += count;
    }

    return total;
}

An explanation on how char *array[] actually works for access wold be appreciated. I believe that it is supposed to be an array of pointers to strings.

4
  • 2
    well, what's your issue? the obvious bug I'm seeing is that you're not resetting count between each word Commented Nov 8, 2017 at 9:19
  • It seems that if (array[i] != NULL) has no meaning. Commented Nov 8, 2017 at 9:22
  • Incase the array has had strings removed. Commented Nov 8, 2017 at 9:25
  • If you are counting bytes, this is easy. If you want to count characters, it can get quite involved. (Multi-byte encoding, combining characters, ...) Commented Nov 8, 2017 at 9:42

4 Answers 4

2
  • You have to increment the index to consider each of the character.

Something like this:-

for (int i = 0; i < len; i++)
{
    if (array[i] != NULL)
    {
        int j=0,count=0;
        while (array[i][j++] != '\0') {
            count++;
        }
        total += count;     
    }

}
  • Also reset the count or add to total at the end of all the calculation.

As an answer to your second question:-


char* array[] is basically denoting an array pointers each pointing to the string literals with which you initialized it.

So once you use array[i] you should now think that it is nothing other than a pointer to a string literal.

Sign up to request clarification or add additional context in comments.

2 Comments

count is defined inside if-block. total += count; : Using count at out of scope. Also including the terminating characters
@BLUEPIXY.: The answer detects the problem right. But thanks for the help
0

You need to reinitialize the variable count inside the for loop for each processed string and to increase the expression *array[i] inside the while loop.

Also it is better when the function has the return type size_t (size_t is the type that is returned by the standard C function strlen and by the operator sizeof)

The function can look as it is shown in the demonstrative program.

#include <stdio.h>

size_t countChars( const char *array[], size_t n )
{
    size_t count = 0;

    while ( n-- )
    {
        if ( array[n] )
        {
            size_t i = 0;
            do { ++count; } while ( array[n][i++] );
        }
    }

    return count;
}

int main(void) 
{
    const char * example[] = { "s", "ss", "sss" };

    printf( "%zu\n", countChars( example, sizeof( example ) / sizeof( *example ) ) );

    return 0;
}

The program output is

9

Each element of this array

char *example[] = {"s", "ss", "sss"};

has type char * and is a pointer to the first character of the corresponding string literal.

Comments

0

Since your array contains string constants you should declare it with const:

const char *example[3];

Without const the compiler will not warn you if you try to assign a character to example[i][j]. For the same reason the formal parameter should also be declared with const.

For a pure function with no side effects it is better to name it so that it reflects the result. Therefor I would use charCount instead of countChars (or maybe totalLength). The focus should be on a noun (namely count or length).

Here is my solution:

#include <stdio.h>

#define LEN(a) (sizeof (a) / sizeof (a)[0])

static int CharCount(const char *strings[], int len)
{
    int result, i, j;

    result = 0;
    for (i = 0; i < len; i++) {
        j = 0;
        while (strings[i][j] != '\0') {
            result++;
            j++;
        }
    }
    return result;
}


int main(void)
{
    const char *strings[] = { "s", "ss", "sss" };

    printf("character count: %d\n", CharCount(strings, LEN(strings)));
}

The length macro LEN is very convenient and is the least error prone way to handle array lengths.

Comments

-1

Yes char *array[] = {"aa", "bb", "cc"} is an array of pointers to strings.

  • array[0] points to "aa"
  • array[1] points to "bb"
  • array[2] points to "cc"

You probably want this:

int countChars(char *array[], int len)
{
  int count = 0;

  for (int arrayindex = 0; arrayindex < len; arrayindex++)
  {
    const char *stringptr = array[arrayindex];
                                // stringptr will point successively
                                // to "s", to "ss" and to "sss"

    while (*stringptr++)
      count++;                  // increment count until NUL character encountered
    count++;                    // one more for NUL character
  }

  return count;
}

int main() {
  char *example[] = { "s", "ss", "sss" };

  int x = countChars(example, 3);   // x contains 9 after the call to countChars
                                    // that is 2 + 3 + 4
}

Instead of hard coding 3 you could use sizeof(example) / sizeof(example[0]).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.