从另一个结构复制到新的或现有的结构

时间:2016-11-29 13:28:16

标签: c struct malloc

我与C联系了大约一个月,我试图为自己和教育目的更好地使用struct和malloc

我真正想做的是制作struct element的深层副本:

  1. 进入新对象

  2. 进入现有对象

  3. 要走的路:

    1)
    1.1_ allocate memory for struct
    1.2_ allocate memory for type
    1.3_ allocate memory for 2d array data
    
    2)
    2.1 free memory of 2d array data with (free)
    2.2 free memory of type
    2.3 same steps as new object
    

    我想要制作的功能

    Element element copyToNewObject (Element _element)
    {
        /*No idea how to start */
    }
    
    Element element copyToExistingObject (Element _element)
    {
        /*No idea how to start */   
    }
    
    
    // Type Element
    typedef struct element * Element;
    

    我的结构元素:

    struct element {
            char* type; /* 2 charactere*/
            int i;
            int j;
            int **data;/* 2d array of i and j */
    };
    

    主要功能调用

    Element element  = initElement();
    

    功能正文

    Element initElement(void) {
    
        Element _element = (Element) malloc(sizeof(Element));   
    
        int position;
    
        if(_element == NULL)
        {
            return NULL;   
        }   
    
        (_element)->type = malloc(2 * sizeof(char));
    
        if((_element)->type == NULL)
        {
            return NULL;   
        }
    
        element->data = malloc(element->i * sizeof(int *));
    
        if(element->data == NULL)
        {
            return NULL;    
        }   
        for( position = 0; position < (element->j) ; position++)
           (element)->data[position] = malloc((element)->j * sizeof(int));
    
        return _element;
    }
    

1 个答案:

答案 0 :(得分:1)

Element* copyToNewObject (Element* origin)
{

    if (!origin)
        return NULL;

    Element* target = malloc(sizeof(*target));

    target->type = malloc(sizeof(*(target->type)) * 3) //which should be 3 chars as specified by Some programmer dude
    *(target->type)     = *(origin->type);
    *(target->type + 1) = *(origin->type + 1);
    *(target->type + 2) = '\0';

    target->i = origin->i;
    target->j = origin->j;

    //declare data
    target->data = malloc((sizeof(*(target->data)) * target->i) + (target->j * target->i * sizeof(**(target->data));

    //point the set of row pointers to their respective rows
    size_t k;
    int* rowpointer = target->data + target->i;
    for (k = 0; k < target->i; k++)
        *(target->data + k) = rowpointer + (k * target->j);

    //copy the data
    for (k = 0; k < i; k++)
        memcpy(*(target->data + k), *(origin->data + k), j);

    return target;

}

void copyToExistingObject (Element* origin, Element* target)
{
    //Same as copyToNewObject but without the delcaration of target or the malloc-ing of the target fields
}

此外,由于我们正在使用malloc,因此我们随后也需要使用free

void ElementFree(Element* element)
{
    free(element->type);
    free(element->data);
    free(element);
}
相关问题