请求解释给定C语言代码的运行逻辑及代码中[]的语法概念
[] Syntax Let’s start by looking at the full code snippet:
#include<stdio.h> int f(int t[]){ return t[0] + t[2]; } int main(void){ int i,a[] = {-2,-1,0,1,2}; i = f(a+2); printf("%d",i); return 0; }
Step-by-Step Running Logic
Array Initialization in
main:
The arrayais initialized with values{-2,-1,0,1,2}. In C, arrays are zero-indexed, so:a[0] = -2,a[1] = -1,a[2] = 0,a[3] = 1,a[4] = 2
Passing the Array to Function
f:
The linei = f(a+2)does two key things:ais the base address of the array (points directly toa[0]). Adding2to this pointer uses pointer arithmetic to move it forward by 2 int-sized steps, soa+2now points toa[2](the value0).- When you pass an array to a function in C, the array name decays to a pointer. Even though
fis declared to takeint t[], this is actually equivalent toint *t(a pointer to an integer). The[]here is just syntax that hints the parameter is meant to be used like an array, but it’s treated as a pointer under the hood.
Execution Inside Function
f:
The function returnst[0] + t[2]. Let’s unpack this:t[0]is the value at the pointert(which isa[2], so0).t[2]is the value 2 positions ahead oftin memory. Sincetpoints toa[2],t[2]translates toa[2+2] = a[4](value2).- Summing these gives
0 + 2 = 2, which is returned tomainand stored ini.
Output:
printf("%d",i)prints the value2, which is the final output of the program.
What’s the [] Syntax in C?
The square bracket operator [] is primarily used for array indexing, but it’s actually syntactic sugar for pointer arithmetic. Here’s the core rule:
- For any pointer or array
xand integery,x[y]is exactly equivalent to*(x + y).
Let’s confirm this with our code:
t[0]→*(t + 0)→*t(the value at the pointert).t[2]→*(t + 2)(the value 2 integers ahead oft).
A fun quirk of this equivalence is that since addition is commutative, y[x] works the same as x[y] (e.g., 2[t] would be identical to t[2] in our function), though this is rarely used in practice because it hurts readability.
When you see int t[] in a function parameter list, remember this is just another way to write int *t—C doesn’t pass entire arrays to functions, only pointers to their first element. The [] syntax is a readability hint that the parameter is intended to be accessed like an array.
内容的提问来源于stack exchange,提问作者Hiren Chafekar

