c++ - C 语言指针的问题
迷茫
迷茫 2017-04-17 14:49:36
0
2
310

结构体的指针运算,编译可以通过,但是运行时出现错误,不知道为什么,求详解!

#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));  
}
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
小葫芦

I don’t understand what you push want to do.

Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template