2014-03-27 43 views
0

我有一個具有多個結構的數組。當我要求用戶在第一次輸入數據時一切正常,但是當我再次詢問數組中的下一個位置時,程序崩潰。如果這種方法不起作用,那麼開始時程序不會崩潰? 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; 
} 
+1

你覺得有多少'student_or_prof' *節點*可以放入分配了* this *的內存中?'stack = malloc(n);'? – WhozCraig

回答

1

您需要malloc結構不n

malloc(sizeof(struct student_or_prof)*n) 

編輯:

而且你的代碼再次崩潰,因爲pinx是雙指針,所以這種操作是無效的:

pinx[*head]->flag = 0; 
既然你不改變什麼 stack點,你最好使用一個指針,而不是雙指針

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

這相當於。

因此,你應該改變你push API:

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

,並調用它像:

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

我試過了,再次崩潰.... – valkon

+0

它在哪裏崩潰?使用GDB或放置一些printfs來定位導致崩潰的行。 – brokenfoot

+0

它在那裏崩潰pinx [* head] - > flag = 0;編輯:stack = malloc(sizeof(struct student_or_prof)* n);這是錯的嗎? – valkon

1

malloc分配給定的字節數。

你必須乘以n與你的struct的大小,以分配足夠的內存。

+0

當然,你是對的,但我已經嘗試過,它再次崩潰 – valkon

0

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

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

順便說一句,你head數量似乎並沒有在所有使用,除了exp1.head,也許會更好,從結構去除head,只是有一個變量head

+0

不,我真的需要在那裏頭。其實一切都很好,赤腳給了我我需要的東西 – valkon

+0

好的,很高興聽到。但是,如果您決定希望'push'能夠增加堆棧的容量(例如,您希望允許用戶輸入名稱而不必事先指定計數),則可能需要返回指針 - 指針版本。 –