Problem with pointers in C

I never knew how to play with pointers to C. But this time I would like to ask your help to solve my problems with pointers. I have a function to push a value onto the 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 changed the last line to stackPtr = & node; This function does not work. Why is my question? What is the difference between * stackPtr = node; and stackPtr = & node;

Any help would be greatly appreciated.

+3
source share
4 answers

stackT *stackPtrdefines stackPtr as a pointer to stackT. The calling function passes an object to stackTthis function.

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

, .

+3
*stackPtr = node;

stackPtr , node.

stackPtr = &node;

stackPtr node, .

, , ( ), . - .

+2

stackPtr ( ), () , . , :

*stackPtr = node;

, .

+1

* stackPtr = node

stackPtr , malloc'd.

* stackPtr = & node

stackPtr , , , .

0

Source: https://habr.com/ru/post/1763545/


All Articles