结构体的指针运算,编译可以通过,但是运行时出现错误,不知道为什么,求详解!
#include<stdio.h>
#include<stdlib.h>
typedef struct Stack{
int * List;
int curNumber;
}Stack, *link;
int main(){
void initst(link *A);
void pus(link *A,int k);
link *A;
int k = 8;
initst(A);
pus(A, k);
return 0;
}
void initst(link *A){
*A = (link#)malloc(sizeof(Stack));
(*A) -> List = (int *)malloc(4 * sizeof(int));
}
void pus(link *A,int k){
*((*A)-> List) = k;
printf("%d \n",*((*A) -> List));
}
PHP中文网2017-04-17 14:51:36
Is your A a secondary pointer? It's actually Stack **A, right?
You modified *A in initst, but you did not initialize A. A points to a random address.
It is better to define the type this way
... }Stack, *PStack;
...
PStack pA; // Note that pA is also a pointer!
PStack *ppA = &pA;
initst(ppA);
Your logic will modify the address stored in pA after calling initst.