指针没有取新值
Pointer not taking new value
对于以下函数:
/*this function removes the topmost item in the stack*/
void pop(Stack * S, NODE * returnNode) {
stackNode * temp;
if(S->root == NULL) {
ERROR("Sorry, cannot pop an empty stack!!\n");
}
else {
temp = S->root;
returnNode = temp->Item;/*x now points to the topmost node*/
S->root = temp->nextItem;/*stack points to the rest of the list*/
free(temp);/*returning memory to the system*/
}
}
我希望 returnNode
指针具有与 temp->Item
相同的值,但是当我检查 GDB
中的值时却没有。我错过了什么吗?
我应该补充一点,temp
值设置正确。
如果你想更新一个指针作为参数,你需要传递它的地址。否则,您只是在更新调用堆栈上的值,该值在范围内是本地的。
void pop(Stack * S, NODE ** returnNode) {
stackNode * temp;
if(S->root == NULL) {
ERROR("Sorry, cannot pop an empty stack!!\n");
}
else {
temp = S->root;
*returnNode = temp->Item;/*x now points to the topmost node*/
S->root = temp->nextItem;/*stack points to the rest of the list*/
free(temp);/*returning memory to the system*/
}
}
你应该 *returnNode = temp->Item;
而不是 returnNode = temp->Item;
。
这样想,
在函数中,您只能修改指针指向的变量,而不能修改指针本身的值,即地址。如果要修改一个指针的值,需要传递一个指向它的指针。
例如
如果你有:
int k = 5, f = 15, *pk = &k, *pf = &f;
而你想切换 pk 和 pf 的值,你需要这样的函数:
void change (int **m, int **n) {
int *help = *m;
*m = *n;
*n = help;
}
change(&pk, &pf);
printf("pk ist %i, pf ist %i\n", *pk, *pf);
/* pk ist 15, pf ist 5;*/
对于以下函数:
/*this function removes the topmost item in the stack*/
void pop(Stack * S, NODE * returnNode) {
stackNode * temp;
if(S->root == NULL) {
ERROR("Sorry, cannot pop an empty stack!!\n");
}
else {
temp = S->root;
returnNode = temp->Item;/*x now points to the topmost node*/
S->root = temp->nextItem;/*stack points to the rest of the list*/
free(temp);/*returning memory to the system*/
}
}
我希望 returnNode
指针具有与 temp->Item
相同的值,但是当我检查 GDB
中的值时却没有。我错过了什么吗?
我应该补充一点,temp
值设置正确。
如果你想更新一个指针作为参数,你需要传递它的地址。否则,您只是在更新调用堆栈上的值,该值在范围内是本地的。
void pop(Stack * S, NODE ** returnNode) {
stackNode * temp;
if(S->root == NULL) {
ERROR("Sorry, cannot pop an empty stack!!\n");
}
else {
temp = S->root;
*returnNode = temp->Item;/*x now points to the topmost node*/
S->root = temp->nextItem;/*stack points to the rest of the list*/
free(temp);/*returning memory to the system*/
}
}
你应该 *returnNode = temp->Item;
而不是 returnNode = temp->Item;
。
这样想,
在函数中,您只能修改指针指向的变量,而不能修改指针本身的值,即地址。如果要修改一个指针的值,需要传递一个指向它的指针。
例如
如果你有:
int k = 5, f = 15, *pk = &k, *pf = &f;
而你想切换 pk 和 pf 的值,你需要这样的函数:
void change (int **m, int **n) {
int *help = *m;
*m = *n;
*n = help;
}
change(&pk, &pf);
printf("pk ist %i, pf ist %i\n", *pk, *pf);
/* pk ist 15, pf ist 5;*/