stackT *stackPtr
определяет stackPtr как указатель на stackT
. Вызывающая функция передает объект stackT
этой функции.
Теперь *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);
Оставьте комментарий, если вам нужно больше разъяснений.