gpt4 book ai didi

c - 将数组节点添加到链表中

转载 作者:行者123 更新时间:2023-12-04 16:27:33 24 4
gpt4 key购买 nike

我必须构建一个链表,每个节点都是一个 16 字节数组。使用适用于单个 uint8_t 值的代码,我对其进行了稍微修改以接受 16 个字节。但是,每当我打印列表时,所有节点都是最后添加的节点。我做错了什么?

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>

struct array_deck
{
uint8_t *val;
struct array_deck *next;
};

struct array_deck *head = NULL;
struct array_deck *curr = NULL;

int sizeOfSet;

struct array_deck *create_list(uint8_t *val)
{
struct array_deck *ptr = (struct array_deck*)malloc(sizeof(struct array_deck));

if(NULL == ptr)
return NULL;

ptr->val = val;
ptr->next = NULL;

head = curr = ptr;
return ptr;
}

void print_list(void)
{
struct array_deck *ptr = head;

while(ptr != NULL)
{
printf("\n");
printf("actually added = ");
for (int i = 0; i < 16; i++) {
uint8_t blah = ptr->val[i];
printf("[%2i] ",blah);
}
ptr = ptr->next;
}

printf("\n");
return;
}

struct array_deck *add_to_list(uint8_t *data, bool add_to_end)
{
printf("array to be added = ");
for (int i = 0; i < 16; i++) {
printf("[%2X] ",data[i]);
}

if(NULL == head)
return (create_list(data));

struct array_deck *ptr = (struct array_deck*)malloc(sizeof(struct array_deck));
if(NULL == ptr)
return NULL;

ptr->val = data;
ptr->next = NULL;

if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}

return ptr;
}

int main(void)
{
printf ("# of arrays >> ");
scanf ("%d", &sizeOfSet);

uint8_t data[16];

for(int i = 1; i<=sizeOfSet; i++){
for (int j = 0; j < 16; j++) {
data[j] = i;
}
printf("\n");
add_to_list(data,true);
}

print_list();

return 0;
}

构建具有 3 个节点的链表的示例运行:

# of arrays  >> 3

array to be added = [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1]
array to be added = [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2]
array to be added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
Program ended with exit code: 0

最佳答案

所有array_deck的-> val都指向相同的内存地址 - main中的局部变量data。您将其覆盖 N 次,这就是它打印最后插入的值的原因。

要解决问题,您应该将data数组复制到新数组中,并将新分配的数组地址分配给ptr->val

struct array_deck *add_to_list(uint8_t *data, bool add_to_end)
{
...

struct array_deck *ptr = (struct array_deck*)malloc(sizeof(struct array_deck));
if(NULL == ptr)
return NULL;

ptr->val = malloc(16*sizeof(uint8_t));
memcpy(ptr->val, data, 16*sizeof(uint8_t));
ptr->next = NULL;

...
}

附注最好删除 create_list 函数并在 add_to_list 中执行分配给 head 的所有逻辑。

关于c - 将数组节点添加到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468789/

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