Is it possible to do the same thing as I did below, but without using []
or ->
.
I don't understand why .*(points + 2)
doesn't work. Shouldn't this replace array?
#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;
}
The result should be 100.
You don't say what is failing in your code, but whatever it is, it's because of buffer overflow.
Here
you can't access
students[2]
because it's the third element, and your array has only two, accessing the third element invokes undefined behavior, and of course the same goes forpoints
.In c, an array index starts at
0
, instead of1
, hence the second element would beAlso don't use that kind of identifier for a type name, it's quite confusing, and generally it's better to make it clear when something is a struct, like in this case.
I would recommend the following
Edit: Since the question was edited now the above content seems not logical or incorrect, the actual problem is that this syntax
is invalid, the obvious way is
or even
A good question would be, Why do you think it should work?