You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组初始化与指针混淆问题:下标运算符等价指针运算在数组初始化中的困惑

数组声明 vs 下标访问:为什么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 n integers.
  • The name array refers to the entire array, not a pointer. Its type is int[n] (an array of n ints), not int*.

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 +n is an expression that performs pointer arithmetic (but array hasn’t been declared yet here, so the compiler would throw an error immediately).
  • *(array +n) dereferences that address, which gives you an int value—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:57:43