gpt4 book ai didi

你能改变 C 非指针类型的内存地址吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:50 24 4
gpt4 key购买 nike

为了完全理解它们,我一直在实现一些 C 数据结构。

这是我对字符串链表的定义:

typedef struct str_linked_list {

const char* data;
struct str_linked_list* next;

} str_linked_list;

这是删除列表第 n 个元素的函数的实现:

void str_remove_at(str_linked_list* list, int index) {
// Invalid index case
if (index < 0) {

fprintf(stderr, "Error, array index < 0\n");
return;

}

str_linked_list* to_delete; // Always gonna need this
// Delete head case
if ( index == 0 ) {

to_delete = list;
// If this node is not the last one save the reference to the remaining ones
if ( to_delete->next != NULL )
list = list->next;

//free(to_delete);
return;

}
// General case
int i = 0;

str_linked_list* buf = list;

for (i = 0; i != index-1; i++) {

if (buf->next != NULL){

buf = buf->next;

} else {

fprintf(stderr, "The list is not that long, aborting operation");
return;

}

}

to_delete = buf->next;

if ( to_delete->next != NULL )
buf->next = to_delete->next;

free(to_delete);

}

到目前为止它运行良好,但我相信我调用它的方式不可能删除头部,这就是 free(head) 被评论的原因。我已经使用以下代码测试了这段代码:

#include "LinkedList.h"

int main() {

str_linked_list l;
l.data = "Hello, World";
l.next = NULL;

str_remove_at(&l, 1);


str_print(&l);

printf("\n\n");

str_remove_at(&l, 0);
str_print(&l);

return 0;
}

我有点弄清楚不将列表初始化为指针会导致难以更改存储该变量的内存地址。我是否必须重新编码库才能将列表初始化为指针或有没有一种方法可以将变量的内存位置分配给另一个地址?

综上所述,我可以这样改变“i”的值吗?

#include "stdlib.h"

void change_value(int* i) {
int* new_alloc = malloc(sizeof(int));
*new_alloc = 1;
i = new_alloc;
}

int main() {
int i = 0;
change_value(&i);
return 0;
}

最佳答案

对于删除列表头部的情况,您有几种选择:

A) 将列表作为 **list 传递,允许您从函数内部分配头部,即调用 str_remove_at(&list, i) 并使用*list 而不是函数内部的 list

B) 从函数返回列表的头部,在这种情况下调用者应该执行 list = str_remove_at(list, i)

C) 要求您的列表在头部有一个“sentinel”元素,该元素永远不会被删除,实际列表从 head->next 开始。这“浪费”了一个列表节点,但当实际的第一个元素不再是特例时,也可以简化其他操作。 (如果你有一个双向链表,这样做的好处会增加。)

D) 不是将指针传递给列表中的节点,而是有一个单独的 str_list_nodestr_linked_list,其中 str_list_node 是您的当前 struct 包含 datanextstr_linked_list 包含 str_list_node *head。然后,当您传递 str_linked_list *list 时,您可以更改 list->head 而不必更改 list 本身。 (这个解决方案可能会被扩展以获得其他好处,比如能够存储 str_list_node *tail 以进行 O(1) 追加。)

关于你能改变 C 非指针类型的内存地址吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com