C语言:数组名加偏移时sizeof运算符的行为是否符合标准定义?
sizeof(arrayName + offset) in C Great question—this is a common point of confusion with array-to-pointer decay in C, so let's unpack it step by step.
Is this behavior defined by the C standard?
Absolutely. The C standard explicitly outlines when an array name is treated as a pointer vs. retaining its array type:
From the C17 standard (6.3.2.1 Lvalues, arrays, and function designators):
Except when it is the operand of thesizeofoperator, 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 when you write arrayName + offset, the array name undergoes array-to-pointer decay—it's converted to a pointer to the first element of the array. The result of this addition is a pointer value, so applying sizeof to it will return the size of a pointer (4 bytes in your 32-bit MinGW environment, 8 bytes on 64-bit systems).
The only exception where sizeof(arrayName) doesn't decay is when the array name is the direct operand of sizeof—that's why it returns the total byte size of the entire array.
How to get the size of the array from offset onward?
If your goal is to calculate the total byte size of the array starting at index offset, you can do this safely with:
size_t remaining_size = sizeof(arrayName) - offset * sizeof(arrayName[0]);
Or, to avoid repeating the element type (more maintainable if the array type changes later):
size_t remaining_size = sizeof(arrayName) - offset * sizeof(*arrayName);
One important caveat: this only works if arrayName is an actual array (not a pointer that's been passed to a function). When you pass an array to a function, it decays to a pointer immediately, so sizeof(arr) inside the function will return the size of a pointer, not the array. In that case, you'll need to pass the total array size as a separate parameter, like:
void process_array(int arr[], size_t total_size, size_t offset) { size_t remaining_size = total_size - offset * sizeof(int); // ... use remaining_size ... } // Call it like: int my_array[10]; process_array(my_array, sizeof(my_array), 3);
内容的提问来源于stack exchange,提问作者Rajesh

