首页 > 解决方案 > 卡住空指针和空字符串检查

问题描述

我是 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]));
     }

}

标签: cstringnullpointerexceptionnullnull-pointer

解决方案


首先,我告诉你,如果你不需要格式转换(使用转换说明符),使用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] != '\0')     // check the first element
          // do operation
         }
          // else 
         return NULL;      //indicate error condition
     }
    

推荐阅读