在struct字段中填充Char *(列表)

时间:2015-05-18 15:58:39

标签: c arrays list pointers struct

通过使用带有“int”键的列表处理“char *”键,我遇到了麻烦。 struct看起来像是:

struct nodo {
char *info;
struct nodo *prec;
struct nodo *succ;
};
typedef struct nodo nodo;

我正在尝试使用一个函数,我用了很多东西来填充struct的int或float字段(显然很适应):

struct nodo *Crealista(void) {
    struct nodo *p, *primo, *back;
    int i, n;
    p = NULL;
    primo = NULL;
    back = NULL;
    printf("Numero di elementi: ");
    scanf("%d", &n);
    assert(n!=0);
    printf("inserisci %d numeri interi positivi: ", n);

for (i=0; i<n; i++) {
    p = malloc(sizeof(struct nodo));
    scanf("%c" /* or maybe s? i need a string for each nodo... */, p->info); 
  // i feel this is the line that needs some more work
    p->prec = back;
    p->succ = NULL;
    if (p->prec)
        p->prec->succ = p;
    back = p;
}

     primo = p;

     while (primo != NULL && primo->prec != NULL)
         primo = primo->prec;

return primo;
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

只需在您提及的行中的&中添加scanf

即可
        scanf(" %c", &p->info); 

并在格式字符串%c之前将空格分配给" %c",以便以您希望的格式显示文字。