前言
我们知道Python、Java等编程语言在进行对象管理时,往往将对象分配在堆内存中。而c/c++中的对象(结构体)数据存储则更灵活。
正文
比如在c/c++中,定义一个结构体对象,表示字符串链表的节点。
typedef struct string_node{
char* str;
struct string_node* next;
}string_node;
/* 用于增加链表节点 */
void add_string_node_to_list(string_node* head,char* str){
string_node* node = (string_node*)malloc(sizeof(string_node));
node->str = (char*)malloc(sizeof(char)*strlen(str)+1);
strcpy(node->str, str);
node->next = NULL;
string_node* temp = head;
// 将链表中的字符串添加到链表尾部
while(temp->next != NULL){
temp = temp->next;
}
temp->next = node;
node->next = NULL;
}
void print_string_node(string_node* head){
string_node* temp = head;
printf("Your string list is: \n");
while(temp){
printf("%s ", temp->str);
temp = temp->next;
}
}
void test02(){
string_node* head = (string_node*)malloc(sizeof(string_node));
head->str = "hello";
head->next = NULL;
int i = 0;
for(i = 1; i < 3; i++){
char str[10];
memset(str, 0, sizeof(str));
sprintf(str, "hello%d", i);
add_string_node(head, str);
}
print_string_node(head);
}
int main(void){
test02();
return 0;
}
从代码中可以看到,链表节点分配在堆内存中,节点中的字符串元素也存储在堆中。这种方式和其它编程语言是相似的做法。其输出结果为:
Your string list is:
hello hello1 hello2
这里一定要注意添加链表节点字符串时,必须将字符串采用复制的方式传递给节点字符串指针,而不是采取直接赋值的方式。
考虑到指针的灵活性,也可以将字符串存储在全局区域中。将增加链表节点到链表的函数修改为:
char l_str[3][10]; // 用于存储节点的字符串数组,每一行对应一个节点字符串
/* 用于增加链表节点 */
void add_string_node_to_list(string_node* head,char* str){
string_node* node = (string_node*)malloc(sizeof(string_node));
// node->str = (char*)malloc(sizeof(char)*strlen(str)+1);
static char i = 0;
node->str = l_char[i++];
strcpy(node->str, str);
node->next = NULL;
string_node* temp = head;
// 将链表中的字符串添加到链表尾部
while(temp->next != NULL){
temp = temp->next;
}
temp->next = node;
node->next = NULL;
}
输出结果与前者相同。
通过这种方式可以减少字符串malloc和free的开销,还可以将链表节点的字符串数据进行存储。但是全局数组无法灵活控制空间大小,可能会出现一些bug。
总结
目前没发现这玩意有什么用处,可能以后会有类似的需求吧!