混淆点
各类语言经常有一些容易让人产生的混淆点,今天我们列举一下:
地址和指针(Addresses and Pointers)
关于地址和指针,在理解变量状态及操作可以说很重要也很基础的概念。之前有写过可以在下面找到。作为补充,下面有个容易混淆的概念。
ini i = 17; int *addressOfI = &i; *addressOfI = 89;
星号有两种不同用法
- 第一种,声明指针:将变量addressOfI声明为 int *, 即指向保存int值的内存地址。
- 第二种,去引用: 访问保存在addressOfI地址中的int值,指针也称为引用,所以通过指针访问某个地址中的数据这一过程,有时也称去引用。
& 运算符,可以得到变量的地址。
int x = 1;
int *y = &x; // &x 变量x地址赋给y指针
printf("x value is %d\n", x); // x的值
printf("x self address is %p\n", &x); // x自身的地址
printf("y stored address is %p\n", y); // y存储的指针地址
printf("y self address is %p\n", &y); //y自身的地址
printf("y stored address is %p\n", *&y);//y存储的地址
简单来讲:
- int *指向的是存储的变量地址,而非自身地址。
- * 指向的是值。
- & 变量的地址。
帧和栈 (Frames and Stack)
为了理解这两个概念,我们先看一个函数执行过程。
#include <stdio.h>
void singSongFor(int numberOfBottles)
{
if (numberOfBottles == 0) {
printf("There are simple no more bottles of beer on the wall.\n");
} else {
printf("%d bottles of beer on the wall. %d bottles of beer.\n", numberOfBottles, numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass it around, %d bottles of beer on the wall.\n", oneFewer);
singSongFor(oneFewer);
printf("Put a bottle in the recycling, %d empty bottles in the bin.\n", numberOfBottles);
}
}
int main(int argc, const char * argv[]) {
singSongFor(4);
return 0;
}
再来看一下它的输出。
4 bottles of beer on the wall. 4 bottles of beer. Take one down, pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall. 3 bottles of beer. Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall. 2 bottles of beer. Take one down, pass it around, 1 bottles of beer on the wall. 1 bottles of beer on the wall. 1 bottles of beer. Take one down, pass it around, 0 bottles of beer on the wall. There are simple no more bottles of beer on the wall. Put a bottle in the recycling, 1 empty bottles in the bin. Put a bottle in the recycling, 2 empty bottles in the bin. Put a bottle in the recycling, 3 empty bottles in the bin. Put a bottle in the recycling, 4 empty bottles in the bin. Program ended with exit code: 0
有没有疑问,比如说为什么后面变成了1234,而不是4321。
Comments:
Email questions, comments, and corrections to hi@smartisan.dev.
Submissions may appear publicly on this website, unless requested otherwise in your email.