By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,083 Members | 1,957 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,083 IT Pros & Developers. It's quick & easy.

Dynamic structure

P: 2
I need a structure to create dynamically at run time through the user input. The input will be given at run time through the key board.
Is it possible to create a structure at run time through c language?
For reference follow the link given below.
https://stackoverflow.com/questions/22084223/creating-a-certain-struct-at-run-time-in-c
Jul 16 '17 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
A structure is part of the code. There is no code at run time. Therefore, you cannot create a struct at runtime.

Instead what you do is define a struct in the code and then use malloc() at runtime to create an instance of the struct dynamically.

Read up on this since you are responsible for deleting anything you create at runtime.

Expand|Select|Wrap|Line Numbers
  1. struct Data
  2. {
  3.    ....your members go here...
  4.  
  5. };
  6.  
  7. In main():
  8.  
  9. Data* ptr = 0;
  10.  
  11. ptr = malloc(sizeof Data);
  12.  
Now use ptr to access the struct members.
Jul 16 '17 #2

Post your reply

Sign in to post your reply or Sign up for a free account.