0

Is there any way, how can I declare 2d field in function, but the size of this field is changing every time, when I turn on and off my program... :)

void 2d_field(char field[what type here][what type here], ...) //let say that size of 2d field isnt constant
{
...
}
Jethro Cao
  • 968
  • 1
  • 9
  • 19
Ghost123
  • 1
  • 2
  • Does this answer your question? [Finding length of array inside a function](https://stackoverflow.com/questions/17590226/finding-length-of-array-inside-a-function) – Yunnosch Mar 01 '20 at 17:05
  • @Yunnosch I don't think so. That's how you find the length of an array that's already being passed, but this is about how to pass it in the first place. – Joseph Sible-Reinstate Monica Mar 01 '20 at 17:12
  • @Yunnosch: That is a terrible alternative question, with answers like stuffing the size into the first element or using a sentinel, on top of being for a single dimension instead of two as this questions requests. – Eric Postpischil Mar 01 '20 at 17:13
  • I will happily update my dupe library with better proposals.But there is no way to provide an array of unknown or non-static size (whether 1D, 2D or whatver D). The size always has to be somehow provided. (zero-terminated strings do not count, I think we agree on that). This basic problem is the same again and again. – Yunnosch Mar 01 '20 at 17:15

1 Answers1

1

Generally, a preferable way for a function to receive two-dimensional arrays with dimensions not known at compile time is to pass the sizes and use those to define the array:

void 2d_field(size_t Rows, size_t Columns, char field[Rows][Columns])

If you must support C implementation that do not support variable-length arrays, then an alternative is to pass a pointer to the first element of the array:

void 2d_field(size_t Rows, size_t Columns, char *field)

and then use manual calculations to refer to array elements. The element in row r and column c is field[r*Columns+c].

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • @Ghost123: What “problem”? A compiler error message? Something else? Be specific. Show the exact code that has the problem. Show the exact problem—the compiler error message or the erroneous program output. – Eric Postpischil Mar 01 '20 at 17:37