为什么我们需要检查字符串长度大于0?

Con*_*ous 3 c string capitalize conditional-statements cs50

我从 CS50 得到这个例子。我知道我们需要检查“s == NULL”以防 RAM 中没有内存。但是,我不确定为什么我们需要在大写之前检查 t 的字符串长度。

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    // Get a string
    char *s = get_string("s: ");
    if (s == NULL)
    {
        return 1;
    }

    // Allocate memory for another string
    char *t = malloc(strlen(s) + 1);
    if (t == NULL)
    {
        return 1;
    }

    // Copy string into memory
    strcpy(t, s);

    // Why do we need to check this condition?
    if (strlen(t) > 0)
    {
        t[0] = toupper(t[0]);
    }

    // Print strings
    printf("s: %s\n", s);
    printf("t: %s\n", t);

    // Free memory
    free(t);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我们需要在大写之前使用“if (strlen(t) > 0)”?

ike*_*ami 10

从概念上讲,当字符串为空时,没有要大写的字符。

从技术上讲,这是不需要的。空字符串的第一个字符是0, 并且toupper(0)0


请注意,strlen(t) > 0也可以写为t[0] != 0或 只是t[0]。无需实际计算字符串的长度来确定它是否为空字符串。

另外,请务必阅读chux 的答案,以获取有关signed 的更正char