C语言指针问题

3

我从来不擅长在C语言中使用指针。但这一次,我想请你帮助我解决指针问题。 我有一个函数,用于将值推入栈中。

void StackPush(stackT *stackPtr, stackElementT element){

 stackNodeT* node = (stackNodeT *) malloc(sizeof(stackNodeT));  

 if (node == NULL){
  fprintf(stderr, "Malloc failed\n");
  exit(1);
 } else {                                   
  node->element = element;
  node->next = StackEmpty(stackPtr)? NULL : *stackPtr; 
  *stackPtr = node;
 }
}

如果我将最后一行更改为stackPtr =&node,则此函数将无法正常工作。我的问题是为什么? * stackPtr = node;和stackPtr =&node之间有什么区别?如有任何帮助,将不胜感激。
4个回答

3

stackT *stackPtrstackPtr定义为指向stackT的指针。函数的调用者将一个stackT对象传递给该函数。

现在,*stackPtr = node;修改了指针stackPtr所指向的值,而stackPtr = &node;修改了指针变量本身的本地值。

stackT *mystack = createStack();
//mystack points to an empty stack

StackPush1(mystack, elem1);//stackpush1 uses *stackPtr = node;
//mystack points to the node with elem1

StackPush2(mystack, elem2);//stackpush2 uses stackPtr = &node;
//the function updates its local copy, not the passed variable
//mystack still points to the elem1
//node with elem2 is not accessible and is a memory leak.

假设我们有int k = 4; 如果我在"main"函数体中输入*ptr = k;,结果应该与ptr = &k;相同吗?
并不完全相同。运行以下代码,您就可以看到差异:
int k = 4;
//declare a pointer to int and initialize it
int *ptr1 = malloc(sizeof(int));
//now ptr1 contains the address of a memory location in heap

//store the current value into the address pointed to by ptr1
*ptr1 = k; /* this line will fail if we hadn't malloced 
              in the previous line as it would try to 
              write to some random location */

//declare a pointer to int 
int *ptr2;
//and assign address of k to it
ptr2 = &k;

printf("Before \n*ptr1 = %d *ptr2 = %d\n", *ptr1, *ptr2);
//change the value of k
k = 5;
printf("After  \n*ptr1 = %d *ptr2 = %d\n", *ptr1, *ptr2);

如果您需要更多澄清,请发表评论。


假设我们有int k = 4; 如果我在“main”主体中输入类似*ptr = k; 的内容(不在函数内部),结果应该与ptr =&k;相同吗? - aminfar

2
*stackPtr = node;

这个操作会取消引用stackPtr并将指向的对象设置为node的值。

stackPtr = &node;

这将把指针stackPtr更改为指向在堆栈上分配的node指针。

基本上,在第一种情况下,您正在更改指针引用的内容(称为指针的referent),但指针本身保持不变。而在第二种情况下,您正在更改指针以引用不同的内容。


1

一旦传入stackPtr(按值传递),它就是一个本地(自动)变量,修改它不会影响任何调用者的自动变量。但是,当您执行以下操作时:

*stackPtr = node;

你正在修改它所指向的对象。


0

*stackPtr = node

将 stackPtr 指向你 malloc 的内容。

*stackPtr = &node

将 stackPtr 指向一个本地变量的地址,一旦从该函数返回,该地址很可能无效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接