Home > Net >  Calculate the length of the array const char**
Calculate the length of the array const char**

Time:10-30

I have not found a solution for such an example, someone can provide it, please.

Thanks for the solution.

#include <stdio.h>

void test(const char** a)
{
   //how to calculate the length of the array "a" here?
   printf("A - %s\n", a[0]);
   printf("B - %s\n", a[1]);
   printf("C - %s\n", a[2]);
}

int main()
{
   const char* array[3] = {"A", "B", "C"};
   test(array);
   return 0;
}

CodePudding user response:

I agree that, especially for compile-time arrays, define the size of the array as an extra variable you pass to your function. If you need to get the length dynamically, this would work:

A simple implementation of tadman's comment: This is basically what functions like strlen do, always reserve one extra entry in your array that indicates that the "array is over now".

#include <stdio.h>

void test(const char** a)
{
    int len = 0;
    while(1) {
        if (*(a len) == 0) {
            break;
        }
        len  ;
    }
    printf("length is %d\n", len);
}

int main()
{
   const char* array[] = {"A", "B", "C", 0};
   test(array);
   return 0;
}

Note that I removed the length from the array definition, it is given implicitly by the length of the definition on the right side. Alternatively, you could swap the line for the following because remaining indexes of arrays are always filled with 0's which in this case makes them nullpointers.

const char* array[4] = {"A", "B", "C"};
  • Related