2

I'm reading some C++ code (SGP4, a satellite propagation code) and I found the following function declaration:

void twoline2rv(char longstr1[130], char longstr2[130], char typerun,
            char typeinput, char opsmode, gravconsttype whichconst,
            double &startmfe, double &stopmfe, double &deltamin,
            elsetrec &satrec);

I'm wondering what it means to say char longstr1[130] in a function argument. Why does the compiler need to know that the array is 130 bytes long? And why not say char *longstr1?

Rodney Price
  • 177
  • 1
  • 8
  • I'd recommend to use `std::array` instead. – πάντα ῥεῖ Jan 30 '19 at 18:55
  • It's not my code. – Rodney Price Jan 30 '19 at 18:56
  • 1
    I've reopened the Q as it appears the OP knows about array decaying. They are wondering why the Author did not use it. – NathanOliver Jan 30 '19 at 18:58
  • 1
    This is one of those sneaky c++ gotchas. In every other case `char longstr1[130]` would mean an array of 130 `char`s. But in function parameters it's actually a `char*` and the size is never enforced or checked. At best, it's an indication of the *expected* array size for others who would use the function. – François Andrieux Jan 30 '19 at 18:59
  • @NathanOliver On rereading I'm not sure about that. They do suggest `char*` as an alternative, but given that they're asking what `char[130]` here _does_ (and that they ask in the title whether the obvious interpretation is possible) I think a broad answer is called for. Dupe probably not directly useful, agreed. – Lightness Races in Orbit Jan 30 '19 at 19:06

2 Answers2

2

This is kind of misleading code. Those parameters literally do mean char *longstr1 (ugh). There is no bounds checking, nothing. You can pass a pointer to an array of any length. Seems you know this already.

Now, one might argue that this approach is self-documenting, but I'd say it's documenting a lie. If the pointer "should" have a specific bound then this ought to be documented with comments above the function's declaration, rather than suggesting to readers that it'll be enforced by type. It's possible that the author thought that!

Ultimately, to really find out why it's been written that way, you should track down the author and ask them. Anything else is guesswork.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Or one could pass by reference which would force passing an array of the stated size. – NathanOliver Jan 30 '19 at 18:59
  • Thanks. This makes sense. The author isn't a software engineer at all. I know why the string length should be 130 characters: the input string is always 130 characters because of the two line element format (see celestrak.com if you want to know more). – Rodney Price Jan 30 '19 at 19:05
1

It's the same thing; the declaration decays to char *longstr1, but it's more informative to someone reading the API that it expects a buffer of exactly 130 characters.

T Percival
  • 8,526
  • 3
  • 43
  • 43