【问题标题】:Dynamically allocate and add a structure inside a linked chain在链接链内动态分配和添加结构
【发布时间】:2014-05-12 11:27:36
【问题描述】:

我面临一个关于结构动态分配的问题,一个包含指向更具体结构的指针的链接链。

链接链代码:

typedef struct Queue Queue;
struct Queue{
    Real* elmt;
    Queue* next;
    Queue* prev;
};

所以,这个结构是循环的,next指向下一个

struct Real(代表)的代码:

typedef struct Real Real;
struct Real{
    int* nb; //int array containing the number
    size_t size;
    int neg; /*0=positive 1=negative*/
    int com; /*-1 = no comma, otherwise integer indicating the position*/
};

所以,如上所述,我希望动态分配一个包含多个元素的队列,所以我创建了这个函数:

Queue* mallocQueueElmt(const Real* arg){
    Queue* res=NULL;

    res=mallocQueue();

    res->elmt=NULL;
    res->elmt=mallocReal(arg->size);

    memmove(res->elmt->nb, arg->nb, sizeof(int)*arg->size);

    res->elmt->com=arg->com;
    res->elmt->neg=arg->neg;

    res->next=res;
    res->prev=res;

    return res;
}

mallocReal() 只返回一个指向 Real 结构的指针,该结构包含一个指针(意味着结构 Real 的成员 nb)指向一个大小等于 arg->size 的 int 数组(动态分配)

这行得通,我用一个函数测试了它:

void printQueue(Queue* arg){
    Queue* cur=NULL;
    cur=arg->prev;

    if(cur == arg->prev){;
        printReal(cur->elmt);
        printf(" ");
    }
    else    
        while(cur != arg){
            cur=cur->next;
            if(cur->elmt){
                printReal(cur->elmt);
                printf(" ");
            }else{
                printf("no element ");
            }
        }


}

但是当我尝试添加一个元素时,感谢这个功能:

Queue* addElement(Queue* arg, const Real* arg1){
    Queue* res=NULL;

    res=mallocQueue();

    res->elmt=NULL;
    res->elmt=mallocReal(arg1->size);

    memmove(res->elmt->nb, arg1->nb, sizeof(int)*arg1->size);

    res->elmt->neg=arg1->neg;
    res->elmt->com=arg1->com;

    res->prev=arg->prev;
    res->next=arg;
    res->prev->next=res;
    arg->prev=res;

    res=arg;

    return res; 
}

并回忆printQueue(),那么只有第二个元素(因此添加addElement())是 显示,并没有发生任何异常,一切似乎都运行良好。

提前感谢您的帮助

【问题讨论】:

    标签: c pointers dynamic struct allocation


    【解决方案1】:

    您在 printQueue 中的 if 语句将始终只打印队列中最后添加的项目。

    试试这样的:

    void printQueue(Queue* arg){
        Queue* cur=arg;
    
        do {
            printReal(cur->elmt);
            printf(" ");
    
            cur=cur->next;
        } while (cur != arg);
    } 
    

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2018-12-30
      相关资源
      最近更新 更多