0
메신저는 print 함수의 모든 국가를 인쇄하여 두 번째 if 문으로 전달할 수 있다고 가정하고 있지만 인쇄하지는 않습니다. 나는 그것이C에서 참조로 구조체 배열의 이름 값을 전달하는 방법은 무엇입니까?
인 것을 안다. 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'를 출력하고 싶을 것입니다. – AlexP
게시 된 코드에 '마법'번호가 포함되어 있습니다. '마법'숫자는 근거가없는 숫자입니다. I.E. 50. 'magic'숫자는 코드를 이해하고 디버그하는 것을 훨씬 더 어렵게 만든다. 게시 된 코드는 그 'magic'번호에 의미있는 이름을 부여하기위한'#define' 문을 가지고 있지만, 전체적으로 의미있는 이름을 사용하지는 않는다. 암호. – user3629249
함수의'scanf()'패밀리 중 하나를 호출 할 때 : 1) 작업이 성공적으로 수행되었는지를 확인하기 위해 반환 값 (매개 변수 값이 아닌)을 항상 확인하십시오. 2) '% s'형식 지정자를 사용하는 경우 항상 입력 필드의 길이보다 1 작은 MAX_CHARACTERS 한정자를 포함하십시오. a) 버퍼 오버플로 및 결과로 나타나는 정의되지 않은 동작을 피하기 위해 b) NUL 바이트는 입력 버퍼에 추가됩니다. – user3629249