gpt4 book ai didi

c - 为什么在尝试使用指针访问数组元素时不使用间接运算符?

转载 作者:行者123 更新时间:2023-11-30 14:37:59 27 4
gpt4 key购买 nike

我有一个程序,要求输入一些学生的信息,然后输入他们的名字、姓氏和学生 ID。我正在尝试打印存储在学生数组中的每个值。但是,我在 Indirection 需要指针操作数('int' 无效)的 printf("%d\n", *(students+i)->studentID); 行上收到错误

我尝试将行更改为 printf("%d\n", (students+i)->studentID); ,它似乎有效。为什么会发生这种情况?为什么我们不需要对上面打印字符的打印语句执行此操作?谢谢

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

typedef struct Students {
char firstName[20];
char lastName[20];
int studentID;
} Student;

void printRecords(Student *students, int size){

for(int i = 0; i < size; i++){
printf("%c\n", *(students+i)->firstName); // prints
printf("%c\n", *(students+i)->lastName); // prints
printf("%d\n", *(students+i)->studentID); // does not print

}
}

int main(int argc, const char * argv[]) {

int number_of_records;

printf("Please enter the number of records you would like to add:\n");
scanf("%d", &number_of_records);

Student *S;
S = (Student*)malloc(sizeof(Student) * number_of_records);

for(int i = 0; i < number_of_records; i++){
printf("First name of student %d\n", i+1);
scanf("%s/n", S[i].firstName);

printf("Last name of student %d\n", i+1);
scanf("%s/n", S[i].lastName);

printf("StudentID of student %d\n", i+1);
scanf("%d/n", &S[i].studentID);
}

printRecords(S, number_of_records);
}

最佳答案

*(students+i)->studentID 相当于 *((students+i)->studentID)

您尝试取消引用该整数,但出现编译错误。

第一个编译正常,因为

*(students+i)->firstName*((students+i)->firstName) 和成员 firstName 相同code> 是一个衰减为 char * 类型指针的数组。您当然可以取消引用指针。

关于c - 为什么在尝试使用指针访问数组元素时不使用间接运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56915607/

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