如何在接受用户输入的typedef结构中打印变量?

huangapple go评论58阅读模式
英文:

How to print variable in typedef struct that takes user inputs?

问题

我正在尝试解决CS50的这个问题,而不使用训练轮。因为不知何故,我只能访问普通版本的VS Code,而不是带有cs50库的版本。请查看我的代码如下。

在执行代码后,它会提示输入两个用户输入,但不会将它们打印出来。它显示分段错误。

谢谢。

#include <stdio.h>
#include <string.h>

typedef struct
{
    char *name;
    int vote;
} 
candidate;

candidate get_candidate(char *prompt);

int main(void)
{
    candidate president = get_candidate("Enter candidate: ");
    printf("%s\n", president.name);
    printf("%i\n", president.vote);                                
}

candidate get_candidate(char *prompt)
{
    printf("%s\n", prompt);

    candidate c;
    printf("Enter a name:");
    scanf("%s", c.name);

    printf("Enter votes:");
    scanf("%i", &c.vote);

    return c;                   //回到主函数
}

希望这对你有帮助。

英文:

I am attempting to do this problem from CS50 without using the training wheels. bc somehow I can only access the regular version of VS code instead of the one that has the cs50 library. See my code below.

After I execute the code, it will prompt for both of the user inputs but it won't print them. It says segmentation fault.

Thank you.

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

typedef struct
{
    char *name;
    int vote;
} 
candidate;

candidate get_candidate(char *prompt);

int main(void)
{
    candidate president = get_candidate(&quot;Enter candidate: &quot;);
    printf(&quot;%s\n&quot;, president.name);
    printf(&quot;%i\n&quot;, president.vote);                                

}

candidate get_candidate(char *prompt)
{
    printf(&quot;%s\n&quot;, prompt);


    candidate c;
    printf(&quot;Enter a name:&quot;);
    scanf(&quot;%s&quot;, c.name);


    printf(&quot;Enter votes:&quot;);
    scanf(&quot;%i&quot;, &amp;c.vote);

    return c;                   //go back to main 
}

答案1

得分: 1

candidate 结构体的 name 成员在 scanf 之前没有正确分配内存。

尝试在 scanf 之前使用 malloc 分配内存:
c.name = (char *)malloc(100 * sizeof(char));

编辑:如评论中提到的,一个更简单的替代方法也可以使用 char[100],除非你有一个超过100个字符的测试用例。

英文:

The name member of the candidate struct isn't being properly allocated before the scanf.

Try allocating memory using malloc before scanf:
c.name = (char *)malloc(100 * sizeof(char));

Edit: As mentioned in a comment, a simpler alternative would also to just go char[100], which should work out fine unless you have a 100+ character testcase.

huangapple
  • 本文由 发表于 2023年6月16日 04:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定