使用结构数组崩溃的程序

时间:2014-03-27 21:39:47

标签: c arrays struct

我有一个包含多个结构的数组。当我要求用户输入数据时,第一次一切正常但当我再次询问数组中的下一个位置时程序崩溃了。如果这个方法不起作用,那么程序一开始就不会崩溃吗? 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;
}

3 个答案:

答案 0 :(得分:1)

您需要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);

答案 1 :(得分:1)

malloc分配给定的字节数。

您必须将n与结构的大小相乘,以分配足够的内存。

答案 2 :(得分:0)

pinx未指向数组,因此pinx[*head]将访问无效内存,除非*head为零。

我认为你的意思是(*pinx)[*head],它访问你通过malloc分配的数组的第N个元素。例如(*pinx)[*head].prof.name等。

是的,除了head之外,您的exp1.head号似乎根本没有被使用,也许最好从结构中删除head ,只有一个变量head