Alex Rivera | Logout

In C how to get number of items in array of pointers to char strings

Asked 2012-12-24T00:53:24.560
9

I want to implement the following function to print the contents of several char strings which are referenced through a pointer array. How can I determine how many pointers there are without passing the total as an argument of the function?

If it was an array of type int then it would be possible to use the sizeof() function but given that each item of my array is a pointer to a char string and each string could be of different length I don't think I can use this approach.

void printCharArray(char *arr[]){

    int length = sizeof(arr) / sizeof(char); /* this does not give correct 
                                          number of items in the pointer array */

    for (int i=1;i<=length; i++) {
        printf("Array item: [%s]",arr[i]);
    }

}
Edit
Report

1 Answer

6

You cannot pass arrays as function arguments in C. Array names decay to pointers to their first element when used as a function argument, and you must separately specify the number of available array elements.

(In the context of a function parameter type, T[] and T* and T[12] are identical, so your function paramter might as well be char ** arr.)

Like so:

void printCharArray(char ** arr, size_t len) { /* ... */ }

int main()
{
    char * arr[10] = { "Hello", "World", /* ... */ };

    printCharArray(arr, sizeof(arr)/sizeof(*arr));
}

(Alternatively you can supply a "first" and a "one-past-the-end" pointer, which might be a bit more natural.)

answered 2012-12-24T00:56:43.893

Your Answer