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.