gpt4 book ai didi

C:将结构体指针类型的值保存到结构体中

转载 作者:行者123 更新时间:2023-11-30 20:08:47 25 4
gpt4 key购买 nike

我定义了一个这样的类型结构:

typedef struct _liste {
int val;
struct _liste *suiv;
} Liste;

但是当我想将 valuer 保存到类型中但它不起作用时我的代码:

Liste A;
for (int i = 0; i<3; i++){
scanf("%d",&A.val);
*A = A.suiv
}

但变量 A 未保存。怎么修?谢谢

最佳答案

typedef struct _liste {
int val;
struct _liste *suiv;
} Liste;

Liste A;
for (int i = 0; i<3; i++){
scanf("%d",&A.val);
*A = A.suiv
}

有 2 个问题

  • *A = A.suiv 无效,您希望 A = *(A.suiv) 尊重类型(出于任何行为)
  • A.suiv 未初始化,您错过了每个新单元格的分配

有效的代码可以是:

Liste * head;
Liste ** p = &head;

for (int i = 0; i != 3; i++) {
*p = malloc(sizeof(Liste));
scanf("%d",&(*p)->val);
p = &(*p)->suiv;
}
*p = NULL;
<小时/>

完整示例:

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

typedef struct _liste {
int val;
struct _liste *suiv;
} Liste;

int main()
{
Liste * head;
Liste ** p = &head;

for (int i = 0; i != 3; i++) {
*p = malloc(sizeof(Liste));
printf("valeur: ");
scanf("%d",&(*p)->val); /* better to check scanf return 1 */
p = &(*p)->suiv;
}
*p = NULL;

/* show result and free ressources */
printf("la liste est :");
while (head != NULL) {
printf(" %d", head->val);
Liste * l = head;
head = head->suiv;
free(l);
}
putchar('\n');
}

编译和执行:

/tmp % gcc -pedantic -Wall -Wextra l.c
/tmp % ./a.out
valeur: 1
valeur: 2
valeur: 3
la liste est : 1 2 3

valgrind下执行

/tmp % valgrind ./a.out
==32505== Memcheck, a memory error detector
==32505== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==32505== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==32505== Command: ./a.out
==32505==
valeur: 1
valeur: 2
valeur: 3
la liste est : 1 2 3
==32505==
==32505== HEAP SUMMARY:
==32505== in use at exit: 0 bytes in 0 blocks
==32505== total heap usage: 3 allocs, 3 frees, 48 bytes allocated
==32505==
==32505== All heap blocks were freed -- no leaks are possible
==32505==
==32505== For counts of detected and suppressed errors, rerun with: -v
==32505== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
<小时/>

如果您不想将列表放在堆中:

#include <stdio.h>

typedef struct _liste {
int val;
struct _liste *suiv;
} Liste;

#define N 3

int main()
{
Liste liste[N];

for (int i = 0; i != N; i++) {
printf("valeur: ");
scanf("%d", &liste[i].val); /* better to check scanf return 1 */
liste[i].suiv = &liste[i + 1];
}
liste[N-1].suiv = NULL;

/* show result (as a list, forget in an array) */
Liste * p = liste;

printf("la liste est :");
while (p != NULL) {
printf(" %d", p->val);
p = p->suiv;
}
putchar('\n');
}

但在这种情况下,最好不要使用列表,而只使用 int 数组;-)

关于C:将结构体指针类型的值保存到结构体中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55396844/

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