This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

What a mess! (about structures)

The following is a part of one of my source file:

struct s{char *p};
struct s code a = {"string1"};
struct s code b = {"string2"};
I wonder how the structures, 'a' and 'b', are arranged in the memory on Cx51 chips. Are they placed consecutively in the order as they are declared, while the two strings are placed somewhere else, or 'a' first then "string1", then 'b' and the last "stirng2"?

  • I don't know the answer to your question, but I just wanted to point out that your program should not rely on the memory allocation pattern of any particular compiler/linker. You can force memory allocation order by incorporating the variables into a bigger structure.

    - mike

  • Your suggestion is really constructive.
    Actually, the problem is originally relevant to structures with bi-direction linkages. In my design, the structures are too large to complie(error: segment too large) if they are dealed as variables when initializing them. So I have to use keyword 'code' to declare them as well as give values of their fields in them. But the linkage pointers can not be initialized correctly due to their declaring orders.
    e.g.

    struct s{ char *p
              struct s *pre, *suc;
    };
    struct s code a = {"string1", &b, &b }; // line 1
    struct s code b = {"string2", &a, &a};  // line 2
    
    Line 1 can not be complied coz structure 'b' hasn't been declared yet.
    Then I have to calculate the value of the pointers of the first sturcture. ('a' in this example) Then how?
    Or is there any other solutions to this dilemma?

  • Do this. It should work.

    struct s{ char *p
              struct s *pre, *suc;
    };
    
    struct s code b;
    
    struct s code a = {"string1", &b, &b }; // line 1
    struct s code b = {"string2", &a, &a};  // line 2
    

    Jon