3 ms·
So the only difference between an Array and an *int is how sizeof() behaves? And how do I pass my Array to a function without losing sight of its size?
by Radle 10y ago
So the only difference between an Array and an *int is how sizeof() behaves?
And how do I pass my Array to a function without losing sight of its size?
- JoeAltmaier 10y agoI don't believe that's possible. Except 'by hand'; pass the size as a separate parameter.
- optymizer 10y agoShort answer: For the user? yes. For the type system? no. To keep track of the length of the array, you can pass the number of elements as a second parameter to the function. Long answer: For arrays with a declared length, the length is included in its type (6.2.5.20, page 42, [1]). Therefore, the type of "int a[5]" is "array of 5 integers". The type of "int*" is "pointer to integer". For arrays without a length, the type is considered 'incomplete' (6.2.5.22). So the C typing system considers these 2 different types. "Except when it is the operand of the sizeof 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." (6.3.2.1.3) sizeof is essentially an exception. "The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer." (6.5.3.4.2) And that's how sizeof is defined. Because it uses the type to compute the size, and the type of arrays include their length, and the type of arrays doesn't change in sizeof expressions, sizeof will return the total number of bytes of all the elements of the array. [1] C11 standard (draft): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf
- shultays 10y agoCheck this one out https://news.ycombinator.com/reply?id=13237674 https://news.ycombinator.com/reply?id=13237674