C中的对象数组



嗨,我想知道如何在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: %sn", i+1, s.name);
  printf("Age: %dn", s.age);
  printf("GPA: %.2lfn", s.gpa);
 }
}
int main(){
    Student s;
    inputStudents(&s);
    printStudents(s);
    return 0;
}

看起来您正在尝试传递一个指针,该指针将在后来有一个新分配的数组。这不是最简单的方法,但是出于教育目的,这是您需要更改以正确做的事情...

您的学生阵列由指针代表。因此,要突变它,您必须将指针传递给指针。

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

现在,如果您进行此更改,则可以按照您的操作方式使用p

p = (Student *)malloc(no * sizeof(Student));
*s = p; // s now points to a pointer to an array of Students

为什么?如果要突变输入,则不能重新分配s,因此,您将指向指针(*s)分配给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: %sn", i+1, s[i].name); // use the ith Student in s
  printf("Age: %dn", s[i].age);
  printf("GPA: %.2lfn", s[i].gpa);
 }
}

最后,在您的inputStudents迭代中,您需要写入p的不同部分:

for(int i = 0; i<no; i++){
    printf("What is student %d name?n", i+1);
    scanf(" %[^n]", &p[i].name); // mutate the ith student in p
    // ...
}

相关内容

  • 没有找到相关文章

最新更新