이 코드에서는 '\0'
끝을 확인하는 for 루프를 사용합니다 . 함수 내에서 문자열이 작동하는 데 항상 길이가 걸리도록 수정해야합니다.
길이를 사용하는 방법에 대해 설명해 주시면
#include <stdio.h>
#include <ctype.h>
#include "dbg.h"
int print_a_message(const char *msg)
{
printf("A STRING: %s\n", msg);
return 0;
}
int uppercase(const char *msg)
{
int i = 0;
// BUG: \0 termination problems
for(i = 0; msg[i] != '\0'; i++) {
printf("%c", toupper(msg[i]));
}
printf("\n");
return 0;
}
int lowercase(const char *msg)
{
int i = 0;
// BUG: \0 termination problems
for(i = 0; msg[i] != '\0'; i++) {
printf("%c", tolower(msg[i]));
}
printf("\n");
return 0;
}
int fail_on_purpose(const char *msg)
{
return 1;
}
@Jonathan Leffler가 제안했듯이 for()
널 문자를 찾는 대신 길이를 기준으로 종료 되도록 루프를 변경하십시오 .
#include <stddef.h>
int uppercase(const char *msg, size_t len)
{
size_t i = 0;
for(i = 0; i < len; i++) {
printf("%c", toupper(msg[i]));
}
printf("\n");
return 0;
}
OTOH, 길이와 널 문자로 종료해야하는 경우 :
int uppercase(const char *msg, size_t len)
{
size_t i = 0;
for(i = 0; msg[i] && i < len; i++) {
printf("%c", toupper(msg[i]));
}
printf("\n");
return 0;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다