gpt4 book ai didi

c - 如何使用指针和动态内存将结构传递到函数中进行打印 [C 编程]

转载 作者:行者123 更新时间:2023-11-30 15:34:36 24 4
gpt4 key购买 nike

我试图将一个结构传递到一个将打印内容的函数中。我正在寻求任何提示或建议。

结构体

struct student
{
char *fname;
char *lname;
float score;
};

创建原型(prototype)

void printStudents(struct student **s, int student_size);

主要功能

int main()
{
int base_number, i;
int students;

struct student *ptr;

printf("Enter Number of Students: ");
scanf("%d", &base_number);
ptr = (struct student*)malloc(base_number * sizeof(struct student));
students = base_number;

printf("\nEnter Student Information\nExample: John Smith 98.50\n\n");

for(i = 0; i < base_number; i++)
{
printf("Student %d: ", i+1);
scanf("%s %s %f", &(ptr+i)->fname, &(ptr+i)->lname, &(ptr+i)->score);
}

printStudents(&ptr, students);

return 0;
}

打印学生函数

void printStudents(struct student **s, int student_size)
{
int i;
struct student *temp = (struct student*)malloc(student_size * sizeof(struct student));

for(i = 0; i < student_size; i++)
printf("%s %s %.2f\n", (temp+i)->fname, (temp+i)->lname, (temp+i)->score);
}

最佳答案

  1. 将指针传递给指针是否有任何要求?直接传ptr不行吗?

  2. 为什么要构建另一个数组 temp?这只是浪费内存..

.

void printStudents(struct student *s, int student_size);

..

printStudents(ptr, students);

...

void printStudents(struct student *s, int student_size)
{
int i;

for(i = 0; i < student_size; i++)
printf("%s %s %.2f\n", s[i].fname, s[i].lname, s[i].score);
}

关于c - 如何使用指针和动态内存将结构传递到函数中进行打印 [C 编程],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com