如何仅使用指针运算访问结构中的数组

How to access an array within a structure using only pointer arithmetic

是否可以像下面那样做同样的事情,但不使用 []->

我不明白为什么 .*(points + 2) 不起作用。这不应该替换数组吗?

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

typedef struct{
    int points[2];
}_student;

int foo(_student *stud);

int main()
{
    int second;
    _student students[2];
    students[1].points[1] = 100;
    second = foo(students);

    printf("%d", second); 
    return 0;
}

int foo(_student *stud) // returns 3rd member of the array within a struct
{
    int second;
    second =  (*(stud+1)).points[1]; // Works
    //second =  (*(stud+1)).*(points+1);  ----> Does not work!

    return second;
}

结果应该是 100。

你没有说你的代码失败了什么,但不管是什么,都是因为缓冲区溢出。

这里

_student students[2];
students[2].points[2] = 100;

你不能访问 students[2] 因为它是第三个元素,而你的数组只有两个,访问第三个元素会调用未定义的行为,当然 points 也是如此。

在 c 中,数组索引从 0 开始,而不是 1,因此第二个元素将是

_student students[2];
students[1].points[1] = 100;

也不要将那种标识符用于类型名称,这很容易混淆,通常最好在某些东西是结构时弄清楚,就像在本例中一样。

我会推荐以下内容

struct student {
    int points[2];
};

struct student students[2];
students[1].points[1] = 100;

编辑: 由于问题现在编辑了上面的内容似乎不符合逻辑或不正确,实际问题是这个语法

second =  (*(stud+1)).*(points+1);  /* ----> Does not work for sure ! */

无效,显而易见的方式是

second =  *((*(stud + 1)).points + 1); /* ----> Does work! */

甚至

second =  *((stud + 1)->points + 1); /* ----> Does work! */

I don't understand why .*(points + 2) doesn't work. Shouldn't this replace array?

一个很好的问题是,为什么你认为它应该有效?