繁体   English   中英

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

[英]C: save value from type of pointer to struct into struct

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

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

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

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数组;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM