Starting from this section, we will learn one of the most important mechanisms in the C language - pointers. Pointers are the soul of the C language. To learn pointers well, we must first learn from memory addresses.
1. Memory address
Memory, actually an internal storage that can hold many bytes of data. Each storage unit is 8 bits, that is, a byte, abbreviated as B. In this way, a plurality of storage units are linearly arranged together to form a storage space of a certain size. 1024 bytes is 1KB, 1024KB is 1MB, and 1024MB is 1GB, 1024GB is 1TB, and so on. In fact, the essence of memory is a storage unit composed of such many bytes.
In order to allow programs to access these memories efficiently, the computer numbers each byte in the memory, starting from 0 and arranging them sequentially. These numbers are consecutive and linear, for example:
These numbers written to memory are called memory addresses. Under the 32-bit architecture, the computer has only 32 memory address buses, so the CPU can only use the memory address of 4GB, while under the 64-bit architecture, the computer has 64 memory address buses, so the memory address that can be used the most at the end . The memory address variable occupies 4 bytes under the 32-bit system, while the memory address occupies 8 bytes under the 64-bit system.
Second, the pointer variable
Next, let's take a look at the pointer variable. When we access the memory address, we need to access the memory content where it is located according to its memory address. The C language provides such a method to access the contents of the memory through the memory address. Like other basic variable types, we can define a variable of a pointer type. This so-called pointer is an ordinary variable. This variable stores a memory address. When defining a pointer variable, it needs to be the pointer type, for example:
char *p0; short *p1; int *p2;
也就是说char *p0表示的是一个指向字符型变量的指针,short *p1表示的是一个指向短整形的指针。int *p2表示的是指向一个整型变量的指针。注意在这三个变量p0、p1和p2都是指针型变量,它们所占用的大小都是4个字节(在64位架构下占8个字节)。他们都是指针型变量,只不过它们所表示的分别是:所指向的内存地址中存放的变量类型分别为字符型变量、短整型变量和整型变量。
我们可以通过&运算符对一个变量取其所在的内存地址,例如并同仁给相应的指针型变量,例如:
char ch = 'A'; short sh = 12; int i = 234; char *p_ch = &ch; short *p_sh = &sh; int *p_i = &i;
这样在指针变量p_ch中就存放了变量ch的内存地址,也就是通过&符可以将ch变量的所在的内存地址取出来再通过=同仁赋值赋值给p_ch变量,同样p_sh中存放存入的是sh的地址,p_i中存放的是i的地址。得到这些内存地址之后就可以根据自己的需要对这个内存地址所在的变量做相应的操作,对地址取其变量的操作过程就是对变量取地址的逆操作,例如
char ch = 'A'; short sh = 12; int i = 234; printf("%d %d %d\n", ch, sh, i); char *p_ch = &ch; short *p_sh = &sh; int *p_i = &i; *p_ch = 1; *p_sh = 2; *p_i = 3; printf("%d %d %d\n", ch, sh, i); 65 12 234 1 2 3
可以看到我们通过&取地址操作就会将这几个变量的地址赋值给了指针变量,再通过*将指针变量取得变量操其内存地址区域的变量。
欢迎关注公众号:编程外星人