Click here to Skip to main content
15,896,387 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey All

I am facing a problem for creating the struct pointer different for every user



C++
#include<conio.h>
struct mine_struct
{
    int a;

};
int main()
{
    for(int i=0;i<=10;i++)
    {
    int num;
    printf("Hey user please enter the no\n");
    scanf("%d",&num);
    if(num==1)
                {
                    //create a struct pointer for every user dynamically
                    //access the a variable

                    //if i do like this
                        struct mine_struct *p =NULL;
                        p->a=21;

                        //Then p i allocated for every 10 runs i want to create the different pointer for different user and also destroy them
                }
    else
        {
            printf("you have not entered the valid no\n");
        }
    }



return 0;
}
Posted

If you have a fixed number of users (say 10) then declare
C
#define USERS 10
struct mine_struct *p[USERS];

and then, at runtime, create and fill the details of proper item, e.g.

C
if (user == 5)
{
  p[user] =(struct mine_struct *) malloc(sizeof(struct mine_struct));
  if (p[user])
    p[user]->a = 21;
}


Then, when you don't need anymore it
C
if ( p[user] )
{
  free(p[user]);
  p[user] == NULL;
}
 
Share this answer
 
You can't do that: you are specifically setting the value of the pointer to null and then trying to access data via it - that won't work under any circumstances.
I would suggest that you need to look at malloc[^] and free[^] but I can't help you much further as your description of what you want to do makes no sense when viewed with your code...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900