0

So I want to create some functions that take arrays as input, but I don't know how many dimensions the array will have.

Is there a way in c to determine how many dimensions an array has? (ideally as a function)

Clifford
  • 88,407
  • 13
  • 85
  • 165
Maximilian
  • 19
  • 1
  • 5
  • 3
    no, that's not possible. You're not even going to create a function prototype that accepts arrays without knowing the dimension. Implement your own data structure – Jean-François Fabre Jun 01 '21 at 13:24
  • 2
    What would be a usecase for such a function? You, as the programmer, are supposed to know the type of a parameter being passed to a function. – Eugene Sh. Jun 01 '21 at 13:29
  • 1
    "some functions that take arrays as input" --> Arrays cannot be received by the function as an array. The usual alternative is to pass a pointer to the data. – chux - Reinstate Monica Jun 01 '21 at 13:36
  • Parse the input data twice: once to find out how many dimensions and their sizes, and again to read the data after allocating memory. – Weather Vane Jun 01 '21 at 14:24

1 Answers1

1

So this is actually a fairly difficult problem in C. Usually this is solved using one of three ways:

  1. Have a special terminating value, like '\0' for strings
  2. Pass the dimensions of the array as a parameter to whatever function you're using
  3. Keep the pointer of the array and its dimension in a struct together

If I remember correctly, there's a way to figure out the size of an allocated array using *nix systems, but I definitely would not recommend doing this. Just keep track of your allocated memory.

Guy Marino
  • 429
  • 3
  • 6
  • Yeah you can figure out the size of the array in some situations, but not its dimensions. https://stackoverflow.com/a/10349610/15801843 –  Jun 01 '21 at 14:42