簡體   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