我从 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)
{ …Run Code Online (Sandbox Code Playgroud)