C|Pointer

typedef

1
2
3
4
5
/* Linked list element */
typedef struct ELE {
char *value;
struct ELE *next;
} list_ele_t;

这里通过 typedef 关键字来定义了一个结构体,并且起了一个别名叫做 list_ele_t

这样以后我们有两种方式来创建这个结构体

1
2
struct ELE *e1;
list_ele_t *e2;

指针

指针本质上是一个变量,他是存储着另一个变量(指针所指变量)的内存地址

指针本身占用内存,用于保存地址值

我们以一个 Hello World 程序来举例说明,就以之前 typedef 的链表结构为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* 定义链表元素结构体 */
typedef struct ELE {
char *value;
struct ELE *next;
} list_ele_t;

int main() {
/* 创建第一个链表元素 */
list_ele_t *first = malloc(sizeof(list_ele_t));
first->value = strdup("Hello");
first->next = NULL;

/* 创建第二个链表元素并链接到第一个元素 */
list_ele_t *second = malloc(sizeof(list_ele_t));
second->value = strdup("World");
second->next = NULL;
first->next = second;

/* 打印链表中的值 */
list_ele_t *current = first;
while (current != NULL) {
printf("%s\n", current->value);
current = current->next;
}

/* 释放内存 */
free(first->value);
free(first);
free(second->value);
free(second);

return 0;
}

指针变量

1
list_ele_t *first = malloc(sizeof(list_ele_t));

这里的 list_ele_t *first 实际上是声明了一个指针变量 first,它的类型是 list_ele_t *

意思是 first 是一个指向 list_ele_t 类型数据的指针

所以实际上 first 这个指针存储的是一个 list_ele_t 类型数据的内存地址。


C|Pointer
http://example.com/2024/06/09/C-Pointer/
作者
Noctis64
发布于
2024年6月9日
许可协议