📜  C指针

📅  最后修改于: 2020-10-04 12:23:22             🧑  作者: Mango

## C地址

``scanf("%d", &var);``

``````#include
int main()
{
int var = 5;
printf("var: %d\n", var);

// Notice the use of & before var
return 0;
}
``````

``````var: 5

## C指针

### 指针语法

``int* p;``

``````int *p1;
int * p2;
``````

``int* p1, p2;``

### 给指针分配地址

``````int* pc, c;
c = 5;
pc = &c;
``````

### 获取指针所指事物的价值

``````int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);   // Output: 5``````

### 改变指针指向的价值

``````int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c);    // Output: 1
printf("%d", *pc);  // Ouptut: 1``````

``````int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc);  // Ouptut: 1
printf("%d", c);    // Output: 1
``````

``````int* pc, c, d;
c = 5;
d = -15;

pc = &c; printf("%d", *pc); // Output: 5
pc = &d; printf("%d", *pc); // Ouptut: -15``````

### 示例：指针的工作

``````#include
int main()
{
int* pc, c;

c = 22;
printf("Value of c: %d\n\n", c);  // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11

*pc = 2;
printf("Value of c: %d\n\n", c); // 2
return 0;
}
``````

``````Address of c: 2686784
Value of c: 22

Content of pointer pc: 22

Content of pointer pc: 11

Value of c: 2
``````

1. `int* pc, c;`

在这里，创建了一个指针pc和一个类型为`int`的普通变量c
由于pcc最初并未初始化，因此指针pc指向无地址或随机地址。并且，变量c有一个地址，但包含随机垃圾值。
2. `c = 22;`

这将22分配给变量c 。也就是说，将22存储在变量c的存储位置中。
3. `pc = &c;`

这将变量c的地址分配给指针pc
4. `c = 11;`

这将11分配给变量c
5. `*pc = 2;`

会将指针pc指向的内存位置的值更改为2。

### 使用指针时的常见错误

``````int c, *pc;

// pc is address but c is not
pc = c; // Error

// &c is address but *pc is not
*pc = &c; // Error

// both &c and pc are addresses
pc = &c;

// both c and *pc values
*pc = c;``````

``````#include
int main() {
int c = 5;
int *p = &c;

printf("%d", *p);  // 5
return 0;
}``````

``int *p = &c;``

``````int *p:
p = &c;``````

``int* p = &c;``