c语言指针的指针
Pointers are one of the most confusing/challenging parts of C, in my opinion. Especially if you are new to programming, but also if you come from a higher level programming language like Python or JavaScript.
在我看来,指针是C中最令人困惑/最具挑战性的部分之一。 尤其是如果您不熟悉编程,但是如果您来自更高级别的编程语言(例如Python或JavaScript)。
In this post I want to introduce them in the simplest yet not-dumbed-down way possible.
在这篇文章中,我想以最简单但不模糊的方式介绍它们。
A pointer is the address of a block of memory that contains a variable.
指针是包含变量的内存块的地址。
When you declare an integer number like this:
当您声明这样的整数时:
int age = 37;
We can use the &
operator to get the value of the address in memory of a variable:
我们可以使用&
运算符来获取变量内存中的地址值:
printf("%p", &age); /* 0x7ffeef7dcb9c */
I used the %p
format specified in printf()
to print the address value.
我使用了printf()
指定的%p
格式来打印地址值。
We can assign the address to a variable:
我们可以将地址分配给变量:
int *address = &age;
Using int *address
in the declaration, we are not declaring an integer variable, but rather a pointer to an integer.
在声明中使用int *address
,我们不是在声明整数变量,而是在声明一个指向integer的指针 。
We can use the pointer operator *
to get the value of the variable an address is pointing to:
我们可以使用指针运算符*
获取地址指向的变量的值:
int age = 37;
int *address = &age;
printf("%u", *address); /* 37 */
This time we are using the pointer operator again, but since it’s not a declaration this time it means “the value of the variable this pointer points to”.
这次我们再次使用指针运算符,但是由于这次不是声明,所以它的意思是“该指针指向的变量的值”。
In this example we declare an age
variable, and we use a pointer to initialize the value:
在此示例中,我们声明一个age
变量,并使用一个指针来初始化该值:
int age;
int *address = &age;
*address = 37;
printf("%u", *address);
When working with C, you’ll find that a lot of things are built on top of this simple concept, so make sure you familiarize with it a bit, by running the above examples on your own.
使用C时,您会发现很多东西都是基于这个简单的概念构建的,因此请确保通过自己运行上述示例来对它有所了解。
Pointers are a great opportunity because they force us to think about memory addresses and how data is organized.
指针是一个很好的机会,因为它们迫使我们考虑内存地址以及数据的组织方式。
Arrays are one example. When you declare an array:
数组就是一个例子。 声明数组时:
int prices[3] = { 5, 4, 3 };
The prices
variable is actually a pointer to the first item of the array. You can get the value of the first item using this printf()
function in this case:
prices
变量实际上是指向数组第一项的指针。 在这种情况下,您可以使用此printf()
函数获取第一项的值:
printf("%u", *prices); /* 5 */
The cool thing is that we can get the second item by adding 1 to the prices
pointer:
很酷的事情是,我们可以通过将prices
指针加1来获得第二个项目:
printf("%u", *(prices + 1)); /* 4 */
And so on for all the other values.
对于所有其他值,依此类推。
We can also do many nice string manipulation operations, since strings are arrays under the hood.
我们还可以执行许多不错的字符串操作操作,因为字符串是内部的数组。
We also have many more applications, including passing the reference of an object or a function around, to avoid consuming more resources to copy it.
我们还有更多的应用程序,包括传递对象或函数的引用,以避免浪费更多的资源来复制它。
c语言指针的指针