c++ - C 语言指针的运算问题
巴扎黑
巴扎黑 2017-04-17 14:49:32
0
2
546

代码的目的是让结构体里面的 List 指针指向申请的一维数组;curNumber表示目前数组里的元素个数;代码编译通过了,但是不能运行出来;求详解!

#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)
Ty80
link *A;
int k = 8;
initst(&A);
...

void initst(link **A){
    *A = (link)malloc(sizeof(Stack));
    (*A) -> List = (int *)malloc(4 * sizeof(int));
}

If you want to change the pointing of a first-level pointer parameter in a function, you must use a second-level pointer

大家讲道理

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.
Of course
PStack pA;
initst(&pA);
is more direct.

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