数组初始化与指针混淆问题:下标运算符等价指针运算在数组初始化中的困惑
int array[n]和int *(array +n)完全不等价 Great question—you’re absolutely right that these two lines are not equivalent, and the confusion stems from mixing up two entirely different uses of square brackets in C. Let’s break this down clearly:
1. The array[n] == *(array +n) equivalence is for expression access, not declarations
The rule you’re thinking of applies when you’re accessing elements of an array (or a pointer that points to a block of memory). For example:
int array[5] = {1,2,3,4,5}; int x = array[2]; // This is exactly the same as int x = *(array + 2);
Here, array (when used in an expression) decays to a pointer to its first element. The square brackets are just syntactic sugar for pointer arithmetic plus dereferencing—nothing more.
2. int array[n] is an array declaration, not a pointer operation
When you write int array[n], you’re not using square brackets as a pointer operator. Instead:
- You’re telling the compiler to allocate a contiguous block of memory capable of holding
nintegers. - The name
arrayrefers to the entire array, not a pointer. Its type isint[n](an array ofnints), notint*.
A quick way to see the difference:
int array[5]; printf("%zu\n", sizeof(array)); // Prints 5 * sizeof(int) (e.g., 20 on 4-byte int systems) int *ptr = array; printf("%zu\n", sizeof(ptr)); // Prints the size of a pointer (e.g., 8 on 64-bit systems)
The array has a size tied to its element count; the pointer is just a variable holding an address.
3. int *(array +n) isn’t even a valid declaration
To make it worse, the line int *(array +n) isn’t a legal way to declare anything in C:
array +nis an expression that performs pointer arithmetic (butarrayhasn’t been declared yet here, so the compiler would throw an error immediately).*(array +n)dereferences that address, which gives you anintvalue—not a type you can use to declare a variable.
Key Takeaway
Square brackets do two completely separate things in C:
- When used in an expression (like
array[2]), they’re pointer arithmetic sugar. - When used in a declaration (like
int array[5]), they define the size of an array type.
These are unrelated syntax rules, so you can’t apply the array[n] == *(array +n) equivalence to declarations.
内容的提问来源于stack exchange,提问作者Scene

