【问题标题】:Dynamic data structure with scanf使用 scanf 的动态数据结构
【发布时间】:2011-02-09 06:57:10
【问题描述】:

我有一个非常基本的问题,感谢您的耐心等待。

我有一个动态数据结构,只有一个整数值和一个指向下一个结构的指针。我正在使用scanf 获取用户输入以获取 5 个值以添加到结构中并尝试在最后打印输出。我在将输入输入到结构中时遇到语法问题。我查看了 StackOverflow 和 Google,但无济于事(可能是因为它太基础了!)

代码如下:

#include <stdio.h>

struct List
{
    int value;
    struct List *nextaddr;
};

int main()
{
    int int1, int2, int3, int4, int5;

    printf("please enter the first integer: ");
    scanf("%d", int1);
    struct List t1 = {int1};

    printf("please enter the second integer: ");
    scanf("%d", int2);
    struct List t2 = {int2};

    printf("please enter the third integer: ");
    scanf("%d", int3);
    struct List t3 = {int3};

    printf("please enter the fourth integer: ");
    scanf("%d", int4);
    struct List t4 = {int4};

    printf("please enter the fifth integer: ");
    scanf("%d", int5);
    struct List t5 = {int5};

    struct List *first;

    first = &t1;
    t1.nextaddr = &t2;
    t2.nextaddr = &t3;
    t3.nextaddr = &t4;
    t4.nextaddr = &t5;
    t5.nextaddr = NULL;

    printf("%i\n%i\n%i\n%i\n%i\n",first->value,t1.nextaddr->value,t2.nextaddr->value,t3.nextaddr->value,t4.nextaddr->value);

    return 0;
}

如何让用户输入到结构中?

【问题讨论】:

    标签: c data-structures input linked-list dynamic-data


    【解决方案1】:

    一些事情-

    通常,当使用链接结构(如链表)时(如本例所示),您使用malloc 为堆上的对象分配内存,而不是在堆栈上。这背后的基本原理是,您希望链接结构的元素比创建它们的函数的寿命更长,因此堆栈分配单个单元格不太可能正常工作。您可能想通过编写类似的内容来创建结构

    struct List* entry = malloc(sizeof(struct List));
    

    作为后续,由于从用户读取链接列表单元格内容并将其添加到列表中的逻辑对于您正在阅读的每个单元格都是相同的,因此您可能不想只复制代码五次。相反,请考虑编写这样的函数:

    struct List* ReadListEntry(void) {
        struct List* entry = malloc(sizeof(struct List));
        /* ... initialize 'entry' ... */
    
        return entry;
    }
    

    这样,您在main 中的代码可以缩短五倍,并且如果您在代码中发现任何错误(就像您所做的那样),您只需更改一次,而不是五次。

    至于你原来的问题,我认为问题在于你在写

    scanf("%d", myValue);
    

    而不是

    scanf("%d", &myValue);
    

    第一个版本不正确,可能会导致运行时崩溃。 scanf 假定您在使用 %d 格式说明符时提供一个指向整数而不是整数的 指针 作为参数,因此明确的 & 符号可能会伤害您。

    结合上面的想法,使用辅助函数来生成堆分配的列表单元,您可能想尝试编写这样的函数:

    struct List* ReadListEntry(void) {
        struct List* entry = malloc(sizeof(struct List));
    
        scanf("%d", &entry->value);
        entry->nextaddr = NULL;
    
        return entry;
    }
    

    鉴于此,您可能可以重写您的 main 函数,使其比您现在拥有的要简单得多。我将把它作为练习留给读者。 :-)

    希望这会有所帮助!

    【讨论】:

    • 这是一个很好的信息——我知道你需要写的任何东西都比你应该写一个函数要多。 malloc 似乎是解决这些问题的方法 - 特别是如果我要创建一个循环以无限期地继续输入值。希望我能投票给你!谢谢!
    【解决方案2】:

    scanf 应该得到整数的地址,如:scanf("%d", &amp;int1);

    【讨论】:

    • 我认为您还有其他问题,但打电话给scanf 但我并没有经常使用c 所以......试着找出来:)。
    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2011-12-12
    • 2019-03-01
    • 1970-01-01
    相关资源
    最近更新 更多