void print(char *arch[], int num){
int i;
for(i=0; i<8; i++)
printf("%s\n", *(arch+i));
}
In this case I knew that arch
was formed by 8 elements, but if I didn't know how can I know it? Is there a way?
void print(char *arch[], int num){
int i;
for(i=0; i<8; i++)
printf("%s\n", *(arch+i));
}
In this case I knew that arch
was formed by 8 elements, but if I didn't know how can I know it? Is there a way?
Since arrays decay to pointers to their first element when passed as arguments to a function, length information is lost as well.
For example:
void bar()
{
int data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printf("%zu\n", sizeof data); // output: 10 * sizeof(int)
foo(data);
}
void foo(int *arg)
{
printf("%zu\n", sizeof arg) // output: sizeof(int *)
}
This is why strings are null-terminated in C: so that when pointers to strings (or arrays decayed to pointers) are passed to string-handling functions, their length can still be determined by incrementing to the null-pointer and keeping count.
There is no way of knowing the length of an array given only a pointer to the array without one of:
There is no way you can know the size of array passed to function. As array decays to pointer to first element.
Compiler will treat.
void print(char *arch[], int num)
as
void print(char **arch, int num)
Thus when you do
sizeof(arch); //It is size of pointer.
Solution: