search

Home  >  Q&A  >  body text

c++ - C 语言指针的问题

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

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

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 14:51:36

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

    reply
    0
  • PHP中文网

    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.

    reply
    0
  • Cancelreply