卡在空指针和空字符串检查中

Stuck with null pointer and empty string check

我是 C 语言和编程新手。我试图制作一个大写程序,但我应该进行空指针检查和空字符串检查。我怎么能继续?我只是想了解一下。

#include <stdio.h>    
#include <stdlib.h>

int *toUpper(char *str)
{
    int i;
    for (i = 0; i < strlen(str); i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            str[i] = str[i] - 'a' + 'A';
        }
    }
    return str;
}

int main(int argc, char **argv)
{
     for (int i = 1; i < argc; ++i)
     {
         printf(toUpper(argv[i]));
     }

}

首先告诉你,如果不需要格式转换(使用转换说明符),使用puts(),而不是printf()

也就是说,您需要为 toUpper() 函数检查两件事:

  1. 访问前需要检查传入参数是否为空指针。你可以对照 NULL 检查传入指针,比如

    int *toUpper(char *str){
        if (str) {             //makes sure `str` is not a NULL pointer
          // do operation
         }
          // else 
         return NULL;      //indicate error condition
     }
    
  2. 您需要检查提供的字符串是否不为空。为此,您可以检查第一个元素是否为 NUL,使用:

    int *toUpper(char *str){
        if (str) {
           if (str[0] != '[=11=]')     // check the first element
          // do operation
         }
          // else 
         return NULL;      //indicate error condition
     }