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

标签 c

我有一个程序,要求输入一些学生的信息,然后输入他们的名字、姓氏和学生 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/

相关文章:

php - JSON - PHP 与 C/C++

Linux静态代码分析工具对比?

c - 如何在C中找到整数的第n位

c - 在 C 中运行 putchar() 函数时 'enter' 输入如何工作?

c++ - 用 C 或 C++ 为 Android 编写应用程序?

c - 如何使用 C 函数中的值

c - 为什么 "union test{ short a,b; char c1,c2,c3,c4;};"将 c1,c2,c3,c4 存储在同一个字节中,有两个可用?

c++ - -fPIC 仅适用于共享库吗?

c - 指针char输出说明

c - C中 'for'循环中的多个条件