I am trying to understand why the following code does not work:
#include <stddef.h>
size_t
foo(const char ** str)
{
size_t i = 0;
while (*str[0])
i++;
return i;
}
int main (int argc, const char ** argv)
{
foo(argv);
}
Why can’t I pass const char ** argv
to foo()
?
The other answer explains why passing char **
to const char **
is not possible, but my question is different.
Clarified and Concise Issue
Why can’t I pass const char ** argv
as an argument to foo()
when foo()
expects const char **
as an argument?
The code does not work because the foo()
function has an infinite loop. The line while (*str[0])
should be changed to while (*str[i])
in order to iterate through the strings correctly. Additionally, the i
variable should be incremented inside the loop. Here’s the corrected code:
#include <stddef.h>
size_t
foo(const char ** str)
{
size_t i = 0;
while (*str[i])
i++;
return i;
}
int main (int argc, const char ** argv)
{
foo(argv);
}
To answer your question:
You can pass const char ** argv
to foo()
when foo()
expects const char **
as an argument. The provided code can be fixed by correcting the loop condition and incrementing the counter variable correctly.