【问题标题】:Input value to struct from scanf从 scanf 向 struct 输入值
【发布时间】:2016-12-27 04:32:15
【问题描述】:

我正在尝试学习 C 中的 struct。代码符合要求,但当我尝试输入一个值时,它会崩溃。我尝试了 int 成员,它有效。

typedef struct node{
    char *productName;
    int price;
    struct node *next;

}node;

int main (){
    node *head = (node*) malloc(sizeof(node));
    printf("Enter a product name: ");
    scanf("%s", &head->productName);
    printf("Product entered:%s",head->productName);
    //scanf("%d", &head->price); // this works
    //printf("Price entered:%d",head->price);

}

【问题讨论】:

标签: c pointers struct scanf


【解决方案1】:

第一个问题,%sscanf() 需要 char * 参数,你传递的是 char **

也就是说,即使在更正之后(删除&),head->productName 也未初始化并且它没有指向有效的内存位置。访问未初始化的内存调用undefined behavior

您需要使指针指向一个有效内存,然后才能读取或写入它。

最后,在使用返回的指针之前,您应该始终检查malloc() 是否成功。

结合所有这些,就像

node *head = malloc(sizeof *head);
if (head) {
    head->productName = malloc(32); //some arbitary size
    if (head->productName) {
        printf("Enter a product name: ");
        scanf("%31s", head->productName);
        printf("Product entered:%s",head->productName);
    }
}

应该做的工作。


注意:一般建议,不要忘记free() 内存分配器函数返回的指针,以避免任何可能的内存泄漏,因为您的代码会变得更大。

【讨论】:

  • 最后但并非最不重要。不要忘记释放你分配的内存
  • @bansi 好吧,这个特殊情况不会有任何区别,仍然是一个有效的观点。 :)
  • 把所有的东西都写在 'if' 中并不是一种好的写作风格,最好只是测试并在 'if' 中失败。只是说。
【解决方案2】:

可能,你需要这样写:

/*Following code is not tested - Just a sample*/
typedef struct node{
    char *productName;
    int price;
    struct node *next;
}node;

int main (){
    node *head = (node*) malloc(sizeof(node));
    if( head == NULL ) 
     /*fail*/
    printf( "Size of product name:");
    scanf( "%d",&size);
    head->productName = malloc(size);
    if( head->productName == NULL ) {
       /*fail*/
    }
    printf("Enter a product name: ");
    scanf("%s", head->productName);
    printf("Product entered:%s",head->productName);
    /*scanf("%d", &head->price); // this works
      printf("Price entered:%d",head->price);*/

    /*Do stuff with node here*/
    free(head->productName);
    free(head);
    return 0;
}

【讨论】:

  • if( head->productName == NULL ) { /*fail*/ }.... scanf("%s", head->productName);.. 整个if 的东西就没用了。假设您正在尝试编写 MCVE。
【解决方案3】:

试试这个

scanf("%ms", &head->productName);

how-can-i-read-an-input-string-of-unknown-length

也许这就是你要找的东西。

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多