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
There is no built-in way to do this as C does not track the number of elements in an array for you like this.
You have a couple of options:
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.)
If you set the element after the last valid element to null then you can do:
void printCharArray(char *arr[]){
for (int i=0; arr[i] != NULL; i++) {
printf("Array item: [%s]",arr[i]);
}
}
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=0;i<=length; i++) {
printf("Array item: [%s]",arr[i]);
}
}
int main()
{
char * arr[10] = { "Hello", "World", /* ... */ };
printCharArray(arr);
}
first I declared y as a global var. htmTags is a *char[]. then in main()
y = 0;
while( htmTags[y] ) {
y++;
}
I did not add null at the end of array. provides actual count of array elements
or this works too for (y=0;htmTags[y];y++) ;