开发者

C : Why isn't my global variable updating?

开发者 https://www.devze.com 2023-04-13 08:04 出处:网络
So I was bored today and decided to kick off the rust in my C skills, but I can\'t explain this: typedef struct Node

So I was bored today and decided to kick off the rust in my C skills, but I can't explain this:

typedef struct Node
{
   struct Node* prev;
   struct Node* next;
   void* data;
} Node_t;

Node_t* head = NULL;

void add(Node_t* head, void* data)
{
   Node_t* newNode = (Node_t*)malloc(sizeof(Node_t));
   Node_t* iterate = head;

   newNode->next = newNode->prev = NULL;
   newNode->data = data;
   if(head == NULL)
   {
   /*printf("Check 0 %x\r\n", newNode);*/
      head = (Node_t*)malloc(sizeof(Node_t));
      head->next = head->prev = NULL;
      head->data = data;
      printf("Check 0.5 %x\r\n", newNode);
   }
   else
   {
      while(iterate->next != NULL)
      {
         iterate = iterate->next;
      }
      iterate->next = newNode;
      newNode->prev = iterate;
   }
}

int main(int argc, char** argv)
{
   int addValue = 0;
   int* printMe = 0;
   Node_t* iterate;

   for(addValue = 0; addValue < 10; addValue++)
  开发者_运维技巧 {
      add(head, &addValue);
      printf("Check 1 %x\r\n", head);
   }

........

The printf statements print the location in memory that my head is pointing at. Every time it is called from the Add() function, it prints some reasonable memory location, but as soon as it returns, it prints 0 (NULL) as the pointer's value. the two print statements are right after the other. So why is C updating my global pointer within the Add() function, but reverting it once that function call ends?


You are passing the node pointer head by value when you call add. You need to pass a pointer to the node pointer head. So you need to pass &head rather than head in order for the modifications to be made to the global.

Make these changes:

void add(Node_t** head, void* data)

Whenever you refer to head in add you need *head rather than head.

Call add like this:

add(&head, &addValue);


Your local head is eclipsing the global head. Consider this simplified fragment:

int head;
void add(int head) {
    head = 7;  // analog to head=malloc() in your case
    printf("head=%d\n", head);
}
int main() {
    add(head);
    printf("head=%d\n", head);
    return 0;
}

As should be obvious from this simple case, updating the local variable head in add does absolutely nothing to the global variable head.


I am rusty on C as well but if I am reading the variables correctly you are not assigning the GLOBAL variable head, you are just passing the location of the pointer (null). The scope of the head variable in your procedure is strictly that, in the procedure and changing that value in the add procedure will not change the global value. I believe if you pass &head you will get the desired affect.

for(addValue = 0; addValue < 10; addValue++)
{
  add(&head, &addValue);
  printf("Check 1 %x\r\n", head);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消