0

I have the following structs of which **seating becomes a 2d array of patrons. I want to bounds check this before placing a patron in a seat. Specifically, if seating is 2x2 and I want to know how to detect a legal insert and catch an out of bounds;

theatre_seating *t;
t->seating[0][0]=some_patron; // how to know this is ok?

and that

t->seating[3][4]=some_patron; // how to know this is not?

The structs.

struct patron {
    char last_name[30];
    char first_name[30];
};
struct theatre_seating {
    struct patron **seating;
};
Muzol
  • 301
  • 1
  • 11
DanielN
  • 21
  • 1

2 Answers2

0

C pointers don't have any built-in means of keeping track of the size of what they point to. The programmer (i.e., you) must implement some way of storing that. One approach to do that would be to add a rows and seats_per_row variable to the theatre_seating struct, then check against them whenever you use it.

  • I figured that out through trial and error. I found a way to get the rows with: int rows=0; for(int i=0;t->seating[i];i++) { rows+=1; } printf("Row size: %d\n", rows) but couldn't iterate t->seating[i][j] in the same manner – DanielN Sep 06 '18 at 01:43
  • That only works if you always put a null at the end of t->seating when you set it up. You can't count on it being like that if you didn't do it explicitly. – Joseph Sible-Reinstate Monica Sep 06 '18 at 01:45
  • Good to know. I did not do that explicitly and probably never will as I don't think that's very clear code. It's much easier just to put row/col variables in the struct and get my data that way. I have not been in C for many years so I'm doing the dance with nuances. Fun, frustrating, fun. Shampoo bottle, rinse, repeat. – DanielN Sep 06 '18 at 13:49
0

What you are encountering is array decay which signifies a loss of size and dimensions when arrays are passed or used as pointers.

From C Committee draft N1570:

6.3.2.1 Lvalues, arrays, and function designators
...
Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

So in this scenario, you will have to store the dimensions and the size in each dimension somewhere if you want to detect an out-of-bounds access.

P.W
  • 26,289
  • 6
  • 39
  • 76