[OCLUG-devel] sizeof an array of pointers

Christopher Smith x at xman.org
Sun Jun 19 22:16:33 PDT 2005


Doug Jolley wrote:

>>Normally libraries like this address
>>the issue either by terminating the array with a null pointer or have a
>>second argument somewhere that specifies the length of the array. I'd
>>check the docs on the library.
>>    
>>
>
>The library does terminate the array with a null pointer.  So, are you
>saying that the way to go is to just loop through the array and count
>the elements?  I don't have any problem with that.  I just thought
>that if there were a better way, I'd rather use it.
>
>Thanks, Chris, for the input.
>  
>
Yeah, if you need to find out the size of the array, that'd be the way 
to do it. Normally you just want to perform some operations over the 
elements of the array so it's less of a hassle. You can save yourself a 
*tiny* bit of overhead for large arrays by using pointer arithmetic. 
Something like this:

char** the_array = library_function(...);
char** end_array = the_array;
while (end_array != 0) {
    ++end_array;
}
/* now we know end_array is pointing just after the last element of the 
array */
size_t number_of_array_elements = (end_array - the_array) / sizeof(char*);

So, that saves you one increment operation inside the loop. Depending on 
the speed of integer divide on your platform (these days it's 
effectively as fast as integer add), this becomes a net win as the array 
gets bigger.

--Chris



More information about the OCLUG-devel mailing list