1. 程式人生 > >C語言中的淺拷貝和深拷貝

C語言中的淺拷貝和深拷貝

淺拷貝

首先看下面這段程式碼:

# include<assert.h>
# include<string.h>
#include <stdlib.h>
typedef struct Node//定義了一個結構體
{
	int size;
	char *data;
}S_Node;
int main()
{
	S_Node node1;
	node1.data = (char *)malloc(sizeof(char)*100);//指標所指向的地址
	assert(node1.data != NULL);
	strcpy(node1.data, "hello world");
	node1.size = strlen(node1.data);
	S_Node node2 = node1;
	printf("%d, %s\n", node1.size, node1.data);
	printf("%d,%s\n", node2.size, node2.data);
	free(node1.data);
	//free(node2.data);error重複釋放
return 0; }

執行結果為:

node2=node1;僅僅完成淺拷貝(僅會將結構體變數的size,data儲存的值給node2)data指向的空間以及其儲存的資料並不會拷貝,即只是拷貝了8個位元組,如下圖,node2.size=node1.size=11,node2.data=node1.data都儲存的只是地址1000

當free(node1.data),後free(node2.data),程式會報錯。原因是free(node1.data);已經將所申請的空間釋放掉了,當執行free(node2.data);就會重複釋放。所以結構體一般不允許直接賦值。

深拷貝

同樣分析下面這段程式碼:

# include<stdio.h>
# include<assert.h>
# include<string.h>
#include <stdlib.h>
typedef struct Node//結構體
{
	int size;
	char *data;
}S_Node;
void CopyNode(S_Node *node3, S_Node node1)//CopyNode 函式實現結構體變數的深拷貝
{
	node3->size = node1.size;
	node3->data = (char *)malloc(node3->size + 1);//申請空間
assert(node3->data != NULL); strcpy(node3->data, node1.data); } int main() { S_Node node1; node1.data = (char *)malloc(sizeof(char)*100); assert(node1.data != NULL); S_Node node3; CopyNode(&node3, node1); printf("%d, %x\n", node1.size, node1.data); printf("%d,%x\n", node3.size, node3.data); free(node1.data); free(node3.data);//釋放申請的空間 return 0; }

node塊空間來儲存node.data的資料,並不是淺拷貝中僅僅拷貝地址。

執行結果為: