英文:
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 <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; //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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论