简体   繁体   中英

How to store an array of values of unknown size in a struct

I currently have this struct that I have created, I have intialised the pointers in main. And I am stuck with the understanding of how to add a value to the pointers then resize it, because it is waiting for user input. The code below is what I in a shortened version, basically I want to know how to add each value of job to the jobNum variable in the struct and resize it so i can store an arbitrary number of values for jobNum. I am quite new to memory allocation.

    typedef struct {
         int* jobNum;
     }JobInfo;

   void get_job(JobInfo* jobCalled, int job){
        jobCalled->jobNum = job;

   }
     void main(int argc, char *argv[]){
         jobCalled.jobNum = malloc(sizeof(int));
    
        while(1){
            //Other Processes
            if (USER_INPUT == 'job'){
                 int job = argv[1];
                 get_job(&jobCalled, job);
           }
        }
    
}

It sounds like you're having trouble understanding allocation. I would suggest learning about linked lists. Basically in a nutshell:

typedef struct{
    void *head;
    void *next;
}myType;
void addElem(myType *ptr){
    myType *new = (myType*)malloc(sizeof(myType));
    ptr->next = new;
    new->next = NULL;
}

This is a barebones way of doing what you're talking about, where the head element points to your first job, but I believe it would suit you to learn about casting, allocation, etc. You will most likely need to create a function that will initialize your head first job as well. You will also likely want to use free to de-allocate memory from the list if you're removing elements. It is also worth noting that it would be better to have a separate type that will be an individual element so that you only allocate one head pointer, but this way is easier if you're having trouble understanding the concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM