【发布时间】:2018-04-26 06:22:27
【问题描述】:
我应该能够打印 printfunction 中的所有国家并将其传递给第二个 if 语句,但它似乎没有打印。我知道这是
printf("%s\n", ctryList[numCountries].countryName);
部分,但我不知道它有什么问题。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
const int MAX_COUNTRY_NAME_LENGTH = 50;
typedef struct CountryTvWatch_struct {
char countryName[50];
int tvMinutes;
} CountryTvWatch;
void PrintCountryNames(CountryTvWatch ctryList[], int numCountries)
{
int i;
for(i = 0; i < numCountries; i++)
{
printf("%s\n", ctryList[numCountries].countryName);
}
return;
}
int main(void) {
// Source: www.statista.com, 2010
const int NUM_COUNTRIES = 4;
CountryTvWatch countryList[NUM_COUNTRIES];
char countryToFind[MAX_COUNTRY_NAME_LENGTH];
bool countryFound = false;
int i = 0;
strcpy(countryList[0].countryName, "Brazil");
countryList[0].tvMinutes = 222;
strcpy(countryList[1].countryName, "India");
countryList[1].tvMinutes = 119;
strcpy(countryList[2].countryName, "U.K.");
countryList[2].tvMinutes = 242;
strcpy(countryList[3].countryName, "U.S.A.");
countryList[3].tvMinutes = 283;
printf("Enter country name: \n");
scanf("%s", countryToFind);
countryFound = false;
for (i = 0; i < NUM_COUNTRIES; ++i) { // Find country's index
if (strcmp(countryList[i].countryName, countryToFind) == 0) {
countryFound = true;
printf("People in %s watch\n", countryToFind);
printf("%d minutes of TV daily.\n", countryList[i].tvMinutes);
}
}
if (!countryFound) {
printf("Country not found, try again.\n");
printf("Valid countries:\n");
PrintCountryNames(countryList, NUM_COUNTRIES);
}
return 0;
}
【问题讨论】:
-
ctryList[numCountries]不存在;数组ctryList只有ctryList[0],ctryList[1],...,直到ctryList[numCountries-1]。你可能想打印ctryList[i].countryName。 -
发布的代码包含一些“神奇”数字。 “魔术”数字是没有基础的数字。 IE。 50. 'magic' numbers 使代码更难理解、调试等。发布的代码确实有一个
#define声明给那个'magic' 数字一个有意义的名称,但在整个代码中没有使用有意义的名称. -
在调用任何
scanf()系列函数时:1) 始终检查返回值(而不是参数值)以确保操作成功。 2) 使用 '%s' 格式说明符时,始终包含一个比输入字段长度小 1 的 MAX_CHARACTERS 修饰符 a) 以避免任何可能的缓冲区溢出和由此产生的未定义行为 b) 为 NUL 留出空间将附加到输入缓冲区的字节。
标签: c arrays struct pass-by-reference