1

I am begginer in C programming. Can you tell me why I can't use one field in struct in another field?

struct example{
    int length;
    int array[length];
}

Can you tell me what's the scope struct has? I know that is just struct tag not real struct variable,but please explain to me.

RobJob
  • 15
  • 4
  • Can you tell what the value of `length` is? Because its value has to be known at compile time. Otherwise, there's no way to know what `sizeof(struct example)` would be. – Fred Larson Nov 17 '21 at 16:59
  • 1
    This is certainly an [XY Problem](https://xyproblem.info/). What are you _actually_ trying to achieve? – Jabberwocky Nov 17 '21 at 17:01
  • Yeah, but I would like to have variable-length array. Or you want to say that, it doesn't matter because anyways we need to know the length of the structure at compile time,right? – RobJob Nov 17 '21 at 17:01
  • BTW: _"Can you tell me what's the scope struct has? I know that is just struct tag not real struct variable"_, it seem you more or less have understood the issue. – Jabberwocky Nov 17 '21 at 17:02
  • @RobJob you can do something like this with a feature called "flexible array member." But this is an advanced feature and as a beginner you should forget about this for the moment and concentrate on the more basic features of the language. – Jabberwocky Nov 17 '21 at 17:03
  • Are you hoping the array will "magically" resize when you change the `length` field? Not going to happen. – Eugene Sh. Nov 17 '21 at 17:03
  • Yeah, I got it completely, sorry for stupid question. I confuse variable-length array with "malloc array" which we can not know length at compile time. Thank you – RobJob Nov 17 '21 at 17:04
  • Not completely. – RobJob Nov 17 '21 at 17:06
  • Do I need to delete my question or leave it? – RobJob Nov 17 '21 at 17:06

1 Answers1

1

length is not a variable, it's a structure member. It can only be used along with a variable that contains that structure type, e.g.

struct example myvar;
myvar.length = 10;

Since the size of the array member has to be known when the variable is declared, it's not possible for it to be dependent on the value of another member of the same structure.

If the size of the array varies, you can use a flexible array member. See What's the need of array with zero elements?

Barmar
  • 741,623
  • 53
  • 500
  • 612