困扰我的部分是最后一个for
循环,我用它来测试数据输入是否正确以及是否正确使用printf
打印。用于打印我输入的数据的三种访问方法对我来说都不是很清楚。
在访问方法#1 中,我设法只使用一个箭头操作符来正确打印数据以访问名称。我无法解决的问题是为什么我能够在没有错误的情况下访问数据?我只使用索引来访问每个production_plant_employees
结构。我知道括号会解除引用,但我仍然不明白那里发生了什么。我尝试写这样的部分:*(production_plant_employees + i)
,但它没有用。
访问方法#2 对我来说完全清楚。
现在访问方法#3 ,这是我认为可行的方法,但它拒绝了。编写时,IDE显示没有错误,但是当我运行程序时,它会停止。
我应该首先访问第一个指针(即production_plant_employees
)中的数据,然后访问第二个指针中的数据(指针basic_info
在结构employee
中) ,然后,当我通过2个指针时,访问我追求的数据(姓名,年龄等等),对吗?
另外,您能否告诉我其他任何可能的方式来访问我之后的数据?
typedef struct basicdata{
char name[15];
char last_name[15];
char gender[2];
int age;
char birthplace[15];
char address[15];
} BASICDATA;
typedef struct job_info {
int employment_year;
char job_position[20];
char employee_pay_grade[10];
int employee_grade;
} JOB_INFO;
typedef struct employee{
BASICDATA *basic_info;
JOB_INFO *job_info;
} EMPLOYEE;
int main () {
int i;
int choice = 0;
EMPLOYEE *production_plant_employees;
printf("Enter number of employees : \n");
scanf("%d", &choice);
production_plant_employees = (EMPLOYEE*)calloc(choice, sizeof(EMPLOYEE));
if (production_plant_employees == NULL) {
printf("An error occured during memory allocation\n");
}
for(i = 0; i < choice; ++i) {
production_plant_employees[i].basic_info = (BASICDATA*)calloc(choice, sizeof(BASICDATA));
if(production_plant_employees[i].basic_info == NULL) {
printf("An error occured during memory allocation\n");
}
production_plant_employees[i].job_info = (JOB_INFO*)calloc(choice, sizeof(JOB_INFO));
if(production_plant_employees[i].job_info == NULL) {
printf("An error occured during memory allocation\n");
}
printf("production_plant_employees[%d].basic_info = %d\t%x\n", i, production_plant_employees[i].basic_info, production_plant_employees[i].basic_info);
printf("production_plant_employees[%d].job_info = %d\t%x\n", i, production_plant_employees[i].job_info, production_plant_employees[i].job_info);
}
for(i = 0; i < choice; ++i) {
fflush(stdin);
printf("Enter name : \n");
fgets(production_plant_employees[i].basic_info->name, 15, stdin);
printf("Name of %d. employee : %s", i, production_plant_employees[i].basic_info->name) //access method#1
printf("Name of %d. employee : %s", i, (production_plant_employees + i)->basic_info->name); //access method #2
printf("Name of %d. employee : %s", i, *(*(production_plant_employees +i)).basic_info->name); //access method #3 ---> why isn't this working?
printf("\n\n");
}
return 0;
}
答案 0 :(得分:3)
正确的方法是(对于访问方法3):
printf("Name of %d. employee : %s", i, (*(*(production_plant_employees +i)).basic_info).name);
首先我们从解引用指针production_plant_employees +i
开始,现在,我们访问成员basic_info
,它也是一个指针&amp;需要使用第二个*
取消引用以访问本地成员name
。
ptr1 = production_plant_employees +i
ptr2 = (*ptr1).basic_info
data = (*ptr2).name
因此(替换ptr2
中的data
:
data = (*(*ptr1).basic_info).name
&安培;最后替换ptr1
:
data = (*(*(production_plant_employees +i)).basic_info).name