News for hackers. Stuff that matters.
Re:Polymorphic Types in C [pdf] by trealira on Wednesday January 24, 2024 @06:32PM (#39124121)
>>One can take the address of an array and then get the same type checking.

> I don't think this is true, C will not include the length in the type.

No, you can take the address of an array of length N, as long as you're content with having a function that requires the array be that particular length. For example, if you wanted to write a function that adds one to every element of an array with ten elements, and require that it must have ten elements, you can write it like this:

  void add_one(int (*array)[10]) {
      size_t i = 0;
      do {
          (*array)[i] += 1;
      } while (++i < 10);
  }
However, you usually don't see people do this, because they want their functions to work on all arrays, regardless of their length. So, they pass a pointer to the first element and a value representing the length.

You will see people pass pointers to arrays when writing functions that operate on 2D arrays, because that's how you pass a pointer to the first element of a 2D array. The address of the first element of an array of size 10 arrays of int, is a pointer to a size 10 array of int.

  // 2D_array_ptr: a pointer to the first element of an (n x 10) 2D array
  void add_one_to_array_of_array10(int (*2D_array_ptr)[10], size_t n) {
      for (size_t i = 0; i < n; ++i) {
          for (size_t j = 0; j < 10; ++j)
              array[i][j] += 1;
      }
  }
In function signatures, array declarations decay to be equivalent to pointers, so you could also write the function signature like this:

  void add_one_to_array_of_array10(int 2D_array_ptr[][10], size_t n)

There are no comments on this comment yet.