[英]Two different pointer syntax in C which one is right and what's the difference between the two?
我了解指针的概念,并且我们在函数中使用它们来优化我们使用的空间。
我没有得到的是在函数中使用它们时的语法。
示例 1:
void fun(int * a)//that means we declared a pointer to an integer type a
{
*a+=1;
}
fun(&b);//calling the function for int b=10;
示例 2:
void fun(int * a)//that means we declared a pointer to an integer type a
{
a+=1;
}
fun(&b);//calling the function for int b=10;
问题:哪一个是正确的,如果他们都是正确的,两者之间有什么区别?
编辑在 AKX 的回答之后:为什么我们在链表中这样做呢? 如果我们想更改 object 的值而不是指针的地址(在这种情况下是双指针),它不应该是 **head 而不是 *head 吗?
void push(struct node **head, int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = *head;
}
push(&head,1);
如果你有int *p
,那么*p
是指向的值,一个int
。 *p += 1
增加int
。 另一方面, p
本身是int *
,即指针。 p += 1
递增指针,使其指向它指向的数组的下一个元素。
这应该打印10 20 35
:
#include <stdio.h>
void foo(int *p)
{
p += 1; /* increment the pointer */
*p += 5; /* add to the pointed-to int */
}
int main(void)
{
int a[3] = {10, 20, 30};
foo(&a[1]); /* address of / pointer to a[1] */
printf("%d %d %d\n", a[0], a[1], a[2]);
}
这里,
struct node* push(struct node **head, int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = *head;
return newnode;
}
head
是指向struct node
的指针,所以*head
是指向struct node
的指针。 这就是我们通常要存储在链表中的内容,即指向下一条数据的指针。 **head
将是一个struct node
,即元素本身,从中分配将是制作数据的副本。
我了解指针的概念,并且我们在函数中使用它们来优化我们使用的空间。
这不是我们使用它们的原因(至少这不是主要原因,在现代系统上, int *
可能比int
占用更多空间) - 我们使用它们是因为这是向参数写入新值的唯一方法。
Remember that C passes all function arguments by value - any change to the formal argument in the function is not reflected in the parameter in the function call. 如果您的 function 写成
void fun( int a )
{
a += 1;
}
并称为
fun( b );
b
中的值不会受到影响 - a
是完全不同的 object,对它的任何更改都不会反映在b
中。 然而,当我们写
void fun( int *a )
{
*a += 1;
}
fun( &b );
我们没有更新a
的值,我们正在更新a
指向的事物的值,在这种情况下是b
。
关于链表示例,它的编写方式不需要head
是一个struct node **
,因为它没有得到一个新的指针值写入它; 你需要把它称为
list = push( &list, new_value );
正确更新列表指针。
如果您想更新head
参数,您只需将head
作为struct node **
传递,如下所示:
void push( struct node **head, int data )
{
struct node *n = malloc( sizeof *n );
if ( n )
{
n->data = data;
n->next = *head; // n->next points to the old head of the list
*head = n; // n becomes the new head of the list
}
}
并将其称为
struct node *list = NULL; // list is initially empty
push( &list, 42 );
push( &list, 300 );
等等
示例 1 *a=+1;
将存储在指针引用的位置的值设置为+1
。
示例 2 a=+1
使指针指向 memory 地址 1(这可能无效)。
a += 1
: 示例 1 递增存储在指针引用的位置的值(因为*
是取消引用运算符)。
示例 2 增加指针本身,使其指向不同的位置,并且增量是指针类型的大小(如果您有数组则方便)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.