我已经与C联系了大约一个月,我试图为自己和用于教育目的使用结构和malloc
的使用更加增强。p>我真正想做的是制作结构元素的深层副本:
-
进入一个新对象
-
进入现有对象
走的方式:
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 */
};
函数在main
中调用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;
}
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) = ' ';
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);
}