c - CS50 复数编译失败
问题描述
我总是在我的本地计算机上处理 Psets 并替换string
为,char *
因此我不必在我的头文件中使用 CS50 库。这是我对为什么我的代码在运行时无法编译的唯一解释check50
该代码在我的机器和 CS50 IDE 上都按预期工作,但check50
仍然给我这个错误:
code failed to compile
Log
running clang plurality.c -o plurality -std=c11 -ggdb -lm -lcs50...
running clang plurality_test.c -o plurality_test -std=c11 -ggdb -lm -lcs50...
plurality_test.c:68:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
plurality_test.c:109:20: error: unknown type name 'string'
int main(int argc, string argv[])
^
1 warning and 1 error generated.
复数.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
char *name;
int votes;
} candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(char name[]);
void print_winner(void);
int search(char name[]);
int main(int argc, char *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;
printf("Number of voters: ");
scanf("%i", &voter_count);
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
char name[10];
printf("Vote: ");
scanf("%s", name);
// 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(char name[])
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes++;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int prev = -1;
int curr;
int id;
for (int i = 0; i < candidate_count + 1; i++)
{
curr = candidates[i].votes;
if (curr > prev)
{
id = i;
prev = candidates[id].votes;
}
}
printf("%s\n", candidates[id].name);
return;
}
解决方案
@Blauelf 回答了这个问题:
检查器代码重命名您的main
函数并附加自己的函数。
存在警告是因为如果您不显式返回值(默认情况下它将返回 0),则返回值仍然定义main
的唯一函数是返回非的函数。void
对于其他函数,返回值是多少取决于编译器,通常取决于 CPU 架构。通过重命名函数,此特殊属性不再适用。没问题,因为它只是一个警告,并且永远不会调用该函数。
然后他们附加自己的main
函数,这就是错误发生的地方:那个人希望你#include <cs50.h>
. 确保为提交添加此行,即使您自己不使用它的功能。
推荐阅读
- java - 两个 oncreate(bundle savedinstancestate) 在同一个活动中?
- flopy - 如何使用具有盐度约束的 flopy 在 SEAWAT 中模拟抽水井?
- python - 获取2点之间xyz坐标列表的最快方法
- javascript - 通过 Ajax 从 Rails 控制器播放音频 (mp3)
- c++ - 具有不可预测的树结构的多线程
- javascript - python-shell的错误处理:如何避免关闭服务器?
- html - HTML:图像不会显示
- spring-boot - Spring Cloud Gateway 作为转发代理
- javascript - 更改 ajax 表单选择框选择 otomatis
- flutter - 如何仅在没有背景的图像内部绘画