5
struct point { 
    int x;
    int y;
};

main() {
    struct point a;
    a.x = 5;
    a.y = 10;
    printf("%d %d", a.x, a.y);
}

Output:

5 10

Here if I want add a member (int z) int the same structure dynamically. What is the procedure?

What I have tried:

struct point {
    int x;
    int y;
};

struct newpoint {
    struct point a;
    int z;
};

I have tried the above steps, through which we have added a new member and the old structure point to new structure newpoint. But this is not what I want, I want to add the new member the same structure dynamically. I got this question in an interview.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
sri
  • 111
  • 3
  • 9

1 Answers1

5

The interviewer that asked you this has set you on a trap.

It's impossible to "dynamically define a struct" in C. It's possible to do "duck-typing in other languages, for example JavaScript, but C structures are compile time definitions and are as static as it gets.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • 1
    If he create a C file in the runtime and compile it as library and load it dynamically he can create structures dynamically. is it correct ? @Amit – Parham Alvani Feb 14 '16 at 20:24
  • 2
    @ParhamAlvani - that won't help since the "master" application won't know the structure of the "dynamic" struct and won't be able to interact with its members by identifiers, just by memory offsets which is as useful as allocating a bulk of memory and doing the same. – Amit Feb 14 '16 at 20:34
  • 1
    @ParhamAlvani: With such unnecessarily extreme measures you can dynamically create structures that the library can use, sure. But not that the existing program can use. Either way, you're stretching the definition of "dynamically define" past breaking point if you include "writing and compiling a whole new program" within the meaning of "dynamic". – Crowman Feb 14 '16 at 20:36
  • Thanks for your explanations.Even I said at the interview, that it is not possible in C , but he mentioned like it is possible like that.. Anyhow i'll try to meet him and get answers . – sri Feb 14 '16 at 21:23