簡體   English   中英

使用結構數組崩潰的程序

[英]Program with array of structs crashes

我有一個包含多個結構的數組。 當我要求用戶輸入數據時,第一次一切正常但當我再次詢問數組中的下一個位置時程序崩潰了。 如果這個方法不起作用,那么程序一開始就不會崩潰嗎? malloc有問題嗎?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



struct student {
    char name[50];
    int semester;
};

struct prof {
    char name[50];
    char course[50];
};

struct student_or_prof {
    int flag;
    int size;
    int head;
    union {
        struct student student;
        struct prof prof;
    }
}exp1;
struct student_or_prof *stack;


void init(int n)
{
   stack = malloc(n);


}

int push(struct student_or_prof **pinx,int *head,int n)
{
    char name[50];

    printf("\nn= %d\n",n);
     printf("\nhead= %d\n",*head);
    if(*head==n)
    {
        printf("Stack is full.\n");
        return 1;
    }


    char x;
    printf("Student or Professor? [s/p] ");
     getchar() != '\n';
    scanf("%c",&x);

    if(x=='s')
    {

        getchar() != '\n';
       pinx[*head]->flag = 0;

       printf("\n\nGive student's name: ");
       fgets(pinx[*head]->student.name,sizeof(pinx[*head]->student.name),stdin);

       printf("\nGive student's semester: ");
       scanf("%d",&(pinx[*head]->student.semester));

       printf("\nName = %s\tSemester = %d",pinx[*head]->student.name,pinx[*head]->student.semester);

    }
    else if(x=='p')
    {
        getchar() != '\n';
       pinx[*head]->flag = 1;

       printf("\n\nGive professor's name: ");
       fgets(pinx[*head]->prof.name,sizeof(pinx[*head]->prof.name),stdin);

       printf("\nGive course: ");
       fgets(pinx[*head]->prof.course,sizeof(pinx[*head]->prof.course),stdin);

       printf("\nName = %s\tCourse = %s\n",pinx[*head]->prof.name,pinx[*head]->prof.course);
    }



    (*head)++;
    printf("\nhead= %d\n",*head);



}


int main()
{
    int n,i;
  printf("Give size: ");
  scanf("%d",&n);

  init(n);

 for(i=0;i<n;i++)
   push(&stack,&exp1.head,n);

    return 0;
}

你需要malloc結構而不是n

malloc(sizeof(struct student_or_prof)*n)

編輯:

並且您的代碼再次崩潰,因為pinx是雙指針,因此此操作無效:

pinx[*head]->flag = 0;

這相當於:

*(pinx + *head)->flag = 0;

由於您沒有更改stack指向,因此最好使用單個指針而不是雙指針。

所以你應該改變你的push API:

int push(struct student_or_prof *pinx,int *head,int n)

並稱之為:

push(stack,&exp1.head,n);

malloc分配給定的字節數。

您必須將n與結構的大小相乘,以分配足夠的內存。

pinx不指向數組,因此pinx[*head]將訪問無效內存,除非*head為零。

我認為你的意思是(*pinx)[*head] ,它訪問你通過malloc分配的數組的第N個元素。 例如(*pinx)[*head].prof.name等。

順便說一下,你的head似乎根本就沒用過,除了exp1.head ,也許最好從結構中移除head ,只有一個變量head

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM