gpt4 book ai didi

c - "Accessing array of structure using pointer"的替代方式

转载 作者:行者123 更新时间:2023-11-30 19:31:50 24 4
gpt4 key购买 nike

此代码接受 struct Student 数组,然后使用指针显示它。该代码使用了不太常见的方法。常见方法显示在该代码本身的单行注释中。

但是,这种方法似乎存在一些问题,因为没有显示正确的“百分比”值。谁能告诉我这个问题的原因是什么?

#include<stdio.h>

struct Student
{
char grade;
int rollNumber;
float percentage;
};

typedef struct Student Student;

void acceptArray(Student*);
void displayArray(Student*);

int main()
{
Student myFriends[3];
Student* p = myFriends;

acceptArray(p);
displayArray(p);
}

void acceptArray(Student* p)
{
int i = 0;
for(i = 0; i < 3; i++)
{
printf("\nEnter grade, roll number, and percentage:\n");
scanf(" %c %d %f",
(p + i),
//&(p + i)->grade
//&p[i].grade
( (Student*)((unsigned int)p + sizeof(char)) + i ),
//&(p + i)->rollNumber
//&p[i].rollNumber
( (Student*)((unsigned int)p + sizeof(char) + sizeof(int)) + i )
//&(p + i)->percentage
//&p[i].percentage
);
}
}

void displayArray(Student* p)
{
int i = 0;
for(i = 0; i < 3; i++)
{
printf("\nGrade is : %c.", *(p + i));
//(p + i)->grade
//p[i].grade
printf("\nRoll number is: %d.", *( (Student*)((unsigned int)p + sizeof(char)) + i ));
//(p + i)->rollNumber
//p[i].rollNumber
printf("\nPercentage is : %.1f.", *( (Student*)((unsigned int)p + sizeof(char) + sizeof(int)) + i ));
//(p + i)->percentage
//p[i].percentage
}
}

最佳答案

您正尝试将结构对象的各个组件地址传递给scanf。你这样做的方式是错误的。这是不对的,因为(摘自《C 引用手册》)。

holes or padding may appear between any two consecutive components or after the last component in the layout of a structure if necessary to allow proper alignment of components in memory. The bit patterns appearing in such holes are unpredictable and may differ from structure to structure or over time within a single structure.

据说它总是更干净,可读,并且更容易以我们通常的方式阅读 struct (&p[i].grade..)。保持简单的事情简单。

关于c - "Accessing array of structure using pointer"的替代方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858628/

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