0
     struct forces{
        double fo[1];
        double ft[1];
    };
    int main(void){
        struct forces frc;
        frc.fo[0]=6;
        frc.fo[1]=56;
        frc.ft[0]=567;
       printf("%.0lf\n",frc.fo[1]);
        return 0;
    } 

Please assist. Why is my printout always frc.ft[0]?

1
  • Welcome to StackOverflow. Is this C or C++? You should tell us the language. That aside, in both languages arrays are 0-based and only include N elements. so int foo[5] has exactly 5 elements, foo[0] ... f[4]. foo[5] does not exist, and neither does frc.fo[1]. Commented Sep 11, 2018 at 0:10

1 Answer 1

1

With your declaration, fo[1] does not exist and writing to it is undefined behavior for C and C++.

Change your declaration to this to make fo[1] a valid element

struct forces{
    double fo[2];
    double ft[1];
};

In C and C++ (and most similar languages) a declaration of foo[5] creates a 5-element array with valid index values of [0] ... [4]. int foo[1] only has a valid index foo[0]

With your code you see fo[1] in place of ft[0] because your compiler placed the two double variables together in memory with no gap (padding) between them.

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

1 Comment

Thank you. This c code. This is a common mistake I overlooked. I will give it a go.

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.