C语言-结构体-创建结构体 程序运行出错问题以及结构体创建和使用问题整理

运行结构体程序时,在创建新的结构体时,程序运行时总是出错,原因:
从而对C语言指针和结构体有了新的认识

PQueue CreateQueue(void)
{
    PQueue Q;
    Q = (PQueue)malloc(sizeof(Queue));//2
    Q->front = Q->rear = 0;
    return Q; 
}
main()
{
    PQueue Q ;
    Q = CreateQueue(); 
}

这里必须要分配空间后才能对Q进行操作,不然PQueue Q;仅仅是建立了
一个指针,但是却在内存空间中没有开辟可用空间,所以需要用malloc
进行开辟空间后,程序运行才不会出错
既只有运行第2句话后,程序才能运行后续程序

/* 可以用数组直接在结构体中进行开创空间 */

typedef struct Queue{
    int data[MAX_SIZE];
    int front,rear;
} Queue, *PQueue;

/* 创建队列. 返回队列首地址 */ 
PQueue CreateQueue(void)
{
    PQueue Q;
    Q = (PQueue)malloc(sizeof(Queue));
    Q->front = Q->rear = 0;
    return Q; 
}

/可以用指针直接在结构体开创空间后在开创空间/

typedef struct Queue{
    int *pBase;
    int front,rear;
} Queue, *PQueue;

/* 创建队列. 返回队列首地址 */
PQueue CreateQueue(void)
{
    PQueue Q;
    Q = (PQueue)malloc(sizeof(Queue));
    Q->pBase = (int*)malloc(sizeof(int) * MAX_SIZE);
    Q->front = 0;
    Q->rear = 0;
    return Q; 
}

主函数

int main()
{
    PQueue Q ;
    //初始化 
    Q = CreateQueue();
}

猜你喜欢

转载自blog.csdn.net/qq_32460819/article/details/81390511