是否可以像下面那样做同样的事情,但不使用 []
或 ->
。
我不明白为什么 .*(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/