C中的对象数组

时间:2017-03-11 21:41:10

标签: c object struct malloc

您好我想知道如何在C中创建一个对象数组。 这是我的代码。这显然只打印出一个对象的信息。我想创建一个学生阵列,然后打印出他们所有的信息。感谢

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

int no;

typedef struct Student{
char name[30];
int age;
double gpa;
}Student;

void inputStudents(Student *s){
Student *p;
printf("Enter how many students you want : ");
scanf("%d", &no); 
p = (Student *)malloc(no * sizeof(Student));
if(p == NULL){
    exit(1);
}

for(int i = 0; i<no; i++){
    printf("What is student %d name?\n", i+1);
    scanf(" %[^\n]", &s->name);
    printf("What is student %d age?\n", i+1);
    scanf(" %d", &s->age);
    printf("What is student %d gpa?\n", i+1);
    scanf(" %lf", &s->gpa);
}


}

void printStudents(Student s){
  for(int i = 0; i<no; i++){
  printf("\n%d.)Name: %s\n", i+1, s.name);
  printf("Age: %d\n", s.age);
  printf("GPA: %.2lf\n", s.gpa);
 }
}

int main(){
    Student s;
    inputStudents(&s);
    printStudents(s);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

看起来你正试图传入一个指针,之后会有一个新分配的数组。这不是最简单的方法,但出于教育目的,您需要改变以正确行事......

您的学生数组由指针表示。因此,要改变它,你必须传入指向指针的指针。

void inputStudents(Student *s){
// should be changed to:
void inputStudents(Student **s){

现在,如果进行此更改,您可以按照{1}}的方式使用它:

p

为什么呢?如果要改变输入,则无法重新分配p = (Student *)malloc(no * sizeof(Student)); *s = p; // s now points to a pointer to an array of Students ,因此,您将指向指针(s)分配给*s

更改main以使其传递指针指针,并释放由p动态分配的内存:

inputStudents

与打印功能类似:

int main(){
    Student *s; // we use a pointer now
    inputStudents(&s); // pass in a pointer to the pointer
    printStudents(s);
    free(s); // because s now points to malloc'd data we no longer need!

    return 0;
}

最后,在void printStudents(Student *s){ // now takes an array of students for(int i = 0; i<no; i++){ printf("\n%d.)Name: %s\n", i+1, s[i].name); // use the ith Student in s printf("Age: %d\n", s[i].age); printf("GPA: %.2lf\n", s[i].gpa); } } 次迭代中,您需要写入inputStudents的不同部分:

p