簡體   English   中英

帶有布爾的分段錯誤 - CS50 多個

[英]Segmentation fault with bool - CS50 plurality

我正在研究 cs50 復數問題。 當我嘗試為不在我的 argv 中的候選人投票時,我預計會打印“無效投票。\n”,但是我的程序以分離錯誤結束。 誰能解釋為什么? 我認為我的布爾投票邏輯可能有缺陷,但我不確定。 謝謝!

#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;
}

…………………………………………………………………………………………………………………………………………………………………………………… ...................................................... .................................................................. ..

在 function vote()循環

for (int i = 0; i < MAX; i++)

正在檢查每條記錄的字符串,包括帶有NULL指針的字符串。
您應該使用candidate_count設置元素的數量。

for (int i = 0; i < candidate_count; i++)

只有在沒有找到名稱匹配時才會出錯,因為循環索引只有超過記錄的名稱數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM