Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a problem with pointers in C

Tags:

c

pointers

I have never been good at playing with pointers in C. But this time I would like to ask for your help to resolve my problems with pointers. I have a function here to push a value into a stack.

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;
 }
}

If I change the last line to stackPtr = &node; this function does not work. My question is why? What's the difference between *stackPtr = node; and stackPtr = &node; ?

Any help would be appreciated.

like image 348
aminfar Avatar asked Nov 19 '25 21:11

aminfar


1 Answers

stackT *stackPtr defines stackPtr as a pointer to stackT. The caller of the function passes a stackT object to this function.

Now, *stackPtr = node; modifies the value pointed to by the pointer stackPtr whereas stackPtr = &node; modifies the local value of the pointer variable itself.

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.

lets say we have int k=4; if I enter something like *ptr = k; in the "main" body (not inside a function), the results should be the same as ptr = &k;?

Not exactly. Run the following code and see the difference for yourself:

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);

Post a comment if you need more clarification.

like image 190
Amarghosh Avatar answered Nov 22 '25 13:11

Amarghosh