[英]Segmentation fault with bool - CS50 plurality
I am working on cs50 plurality problem.我正在研究 cs50 复数问题。 When I try to vote for a candidate that wasn't in my argv I expected "Invalid vote.\n" to be printed however my program ends in Sementation fault.当我尝试为不在我的 argv 中的候选人投票时,我预计会打印“无效投票。\n”,但是我的程序以分离错误结束。 Could anyone explain why?谁能解释为什么? I think my logic for my bool vote may be flawed but I am not sure.我认为我的布尔投票逻辑可能有缺陷,但我不确定。 Thank you!谢谢!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < MAX; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
return;
}
....................................... ....................................... ....................................... ................................... …………………………………………………………………………………………………………………………………………………………………………………… ...................................................... .................................................................. ..
In function vote()
the loop在 function vote()
循环
for (int i = 0; i < MAX; i++)
is checking every record's string, including those with a NULL
pointer.正在检查每条记录的字符串,包括带有NULL
指针的字符串。
You should use candidate_count
the number of elements set.您应该使用candidate_count
设置元素的数量。
for (int i = 0; i < candidate_count; i++)
It only goes wrong when a match for a name is not found, because the loop index only then exceeds the number of names recorded.只有在没有找到名称匹配时才会出错,因为循环索引只有超过记录的名称数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.