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

标签 c struct 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] 因为它是第三个元素,而你的数组只有两个,访问第三个元素会调用未定义的行为,当然 也是如此点

在 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?

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

关于c - 如何仅使用指针运算访问结构中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062185/

相关文章:

serialization - Coldfusion:通过 url 将结构作为字符串传递

javascript - JavaScript 中的结构体数组

c - 指针运算

不寻常架构的 C 指针算法

c - 为传递给函数的数组指针初始化内存时出现段错误

C - Switch-case 打印 case 两次

c - 以编程方式检测信号发生位置的可移植方法

c++ - C++ 中 if 语句中 int 和 int 的澄清

go - 在Go中比较结构

c++ - 指针算术表达式是否算作指令?