C:将指针类型的值保存到struct中

时间:2019-03-28 11:47:18

标签: c pointers struct

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

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
    }

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

1 个答案:

答案 0 :(得分:2)

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

的数组