简体   繁体   English

如何在结构中存储未知大小的值数组

[英]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.我目前有我创建的这个结构,我已经在 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.下面的代码是我的简化版本,基本上我想知道如何将作业的每个值添加到结构中的 jobNum 变量并调整它的大小,以便我可以为 jobNum 存储任意数量的值。 I am quite new to memory allocation.我对 memory 分配很陌生。

    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.这是做你正在谈论的事情的准系统方式,其中 head 元素指向你的第一份工作,但我相信它适合你学习铸造,分配等。你很可能需要创建一个 function也会初始化你的 head first job。 You will also likely want to use free to de-allocate memory from the list if you're removing elements.如果要删除元素,您还可能希望使用 free 从列表中取消分配 memory。 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.还值得注意的是,最好有一个单独的类型,它将是一个单独的元素,这样您只分配一个头指针,但如果您在理解这个概念时遇到困难,这种方法会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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