6 ms·
C arrays “know” their size. (String literals do too.)
by exprA 10y ago
C arrays “know” their size. (String literals do too.)
- veli_joza 10y agoYou can sizeof them if the declaration is in scope. If you pass them as function argument, this information is not obtainable inside function. You have to pass length as well. This is not very elegant and sometimes you elect to process them without using functions just because you can iterate them easier.
- mfukar 10y agoNow, at one point, you stopped talking about arrays and started talking about pointers.
- veli_joza 10y agoExactly. When array is passed into function, you lose length information and array construct is reduced to pointer. Array syntax is just synthetic sugar for dereferencing pointer with offset.
- mfukar 10y agoThis discussion won't get very far if all you think arrays are is syntactic sugar. The array type is useful - think in terms of a static analyser if it helps - in different ways than pointers.
- cyphar 10y ago"array syntax" != "arrays". He means things like a[i]. Arrays are only really arrays in their local scope, if you pass them to functions they suddenly are pointers (but for some insane reason, C compilers let you specify "the size of the array in a function argument" which doesn't actually compile to any code).
- jandrese 10y agoThat's because C tosses out all of that array state information at the drop of a hat once you start passing them around to functions. Worse, it's an easy way to get burned on the sizeof() function, especially if you at some point refactor the code and put that chunk in a function separate from the original declaration. This is why C programmers get gunshy about relying on that information and instead just treat strings like pointers all of the time.
- mfukar 10y ago> This is why C programmers get gunshy about relying on that information and instead just treat strings like pointers all of the time. Good programmers do nothing of the sort.
- ArkyBeagle 10y agoSo roll your own struct based solution to where the size is now state. If you're talking about the old stdlib.h calls, don't use them with blind pointers where the size isn't known. I'd say use the "n" versions but you don't even have to do that. 'C' gets easier when you do faux RAII and make "objects" with internal state, at least think about not using dynamic allocation for everything and think a little bit about what might make the API usable by the extremely lazy.