1
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?

2 Answers2

3

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:

  1. A "length" parameter
  2. A sentinel value indicating the end of the array (such as the null-terminator for strings)
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • Should your code example have `sizeof(data)` rather than `sizeof data`? Or is there some C magic I'm not aware of? – Catsunami Jan 30 '19 at 20:43
  • @Catsunami `sizeof` only requires parentheses when passing a data type, not an instance of a variable (or object in C++) – Govind Parmar Jan 30 '19 at 20:44
1

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:

  1. You can pass size of array additional to function as parameter.
  2. Have known value at the end of the array and loop until you find the expected value.
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44