Skip to content

Commit

Permalink
更新 C 笔记,指针和数组的关系。
Browse files Browse the repository at this point in the history
  • Loading branch information
jacky committed May 22, 2024
1 parent f178ba9 commit 85431f3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 7 deletions.
14 changes: 7 additions & 7 deletions .obsidian/workspace.json
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,13 @@
},
"left-ribbon": {
"hiddenItems": {
"vscode-editor:Create Code File": false,
"switcher:Open quick switcher": false,
"graph:Open graph view": false,
"canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false,
"templates:Insert template": false,
"command-palette:Open command palette": false
"vscode-editor:新建代码文件": false,
"switcher:打开快速切换": false,
"graph:查看关系图谱": false,
"canvas:新建白板": false,
"daily-notes:打开/创建今天的日记": false,
"templates:插入模板": false,
"command-palette:打开命令面板": false
}
},
"active": "3ec641745c4ff14c",
Expand Down
49 changes: 49 additions & 0 deletions docs/OS/C.md
Original file line number Diff line number Diff line change
Expand Up @@ -764,4 +764,53 @@ void swap(int *x, int *y) {
}
```
### 指针与数组
在 C 语言中指针与数组的关系十分密切。一般来说,用指针编写的程序比用数组下标编写的程序执行速度更快,但另一方面,用指针实现的程序理解起来稍微困难一些。

定义个长度为 10 的数组 a,`a[i]` 表示数组的第 `i` 个元素。
```c
int a[10];
```

定义一个指向整型对象的指针 `pa`,并且将指针 `pa` 指向数组 a 的第 0 个元素。
```c
int *pa;
pa = &a[0];
```

如果 `pa` 指向数组中的某个特定元素,那么,根据指针运算的定义,`pa + 1` 将指向下一个元素。因此,如果 pa 指向 `a[0]`,那么 `*(pa + 1)` 引用的是素组元素 `a[1]` 的内容,`pa + i` 是数组元素 `a[i]` 元素的地址,`*(pa + i)` 引用的是数组元素 `a[i]` 的内容。无论数组 a 中元素的类型或者数组的长度是什么,以上结论都成立。

根据定义,数组类型的变量或表达式的值是该数组第 0 个元素的地址。下面两条赋值语句等价。
```c
pa = &a[0];
pa = a;
```

对数组元素 `a[i]` 的引用也可以写成 `*(a + i)` 这种形式,因此 `&a[i]``a + i` 的含义也是相同的。响应地,如果 pa 是个指针,那么,在表达式中也可以在它后面加下表。`pa[i]``*(pa + i)` 是等价的。

但是,数组名和指针有一个不同之处,指针是一个变量,因此,在 C 语言中语句 `pa = a``pa ++` 都是合法的。但数组名不是变量,因此,类似与 `a = pa``a++` 形式的语句都是非法的。

当把数组名传递给一个函数时,实际上传递的时该数组第一个元素的地址。因此在函数定义中,形参 `char s[]``char *s` 是等价的。
```c
#include <stdio.h>

int str_len(char *s);

int main() {
char s1[] = {'a', 'b', 'd', '\0'};
char *s2 = "hello world!";

printf("s1 len: %d\n", str_len(s1 + 1)); // 2
printf("s2 len: %d\n", str_len(s2)); // 12
}

int str_len(char *s) {
int n;
for(n = 0; *s != '\0'; s ++) {
n ++;
}
return n;
}
```

0 comments on commit 85431f3

Please sign in to comment.