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

47 views Asked by At

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.

1

There are 1 answers

4
Iharob Al Asimi On BEST ANSWER

You don't say what is failing in your code, but whatever it is, it's because of buffer overflow.

Here

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

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 for points.

In c, an array index starts at 0, instead of 1, hence the second element would be

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

Also 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

struct student {
    int points[2];
};

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

Edit: Since the question was edited now the above content seems not logical or incorrect, the actual problem is that this syntax

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

is invalid, the obvious way is

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

or even

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

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

A good question would be, Why do you think it should work?