0

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
  • second = *((*(stud+1)).points+1); Commented Jun 25, 2015 at 23:29

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

4 Comments

I notice now I made a mistake there... but it surprisingly works. I'll change my code in a second.
@Firmus it's not surprisingly, it's because undefined behavior is undefined. And do you mean that now you will make my answer wrong because that's not the question?
I'm sorry... but you didn't answer my question in the first place.
@Firmus Now I did answer your question, despite the fact that your question is not a good one, because it's very hard to understand what you're asking, but it's obvious what you're asking from your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.