修复检查'\ 0'以获取字符串的长度

时间:2014-10-24 15:59:38

标签: c null

在这段代码中,我使用了仍然检查'\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;
}

1 个答案:

答案 0 :(得分:2)

正如@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;
}