c - 卡住空指针和空字符串检查
问题描述
我是 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()
功能检查两件事:
您需要在访问之前检查传入的参数是否为空指针。您可以检查传入的指针
NULL
,如int *toUpper(char *str){ if (str) { //makes sure `str` is not a NULL pointer // do operation } // else return NULL; //indicate error condition }
您需要检查提供的字符串是否不为空。为此,您可以
NUL
使用以下方法检查第一个元素是否为:int *toUpper(char *str){ if (str) { if (str[0] != '\0') // check the first element // do operation } // else return NULL; //indicate error condition }
推荐阅读
- r - 在 R 脚本中选择了未定义的列
- python - 使用 numpy 清理和连接包含特殊字符的 2D 掩码字符串数组
- angular - 使用量角器在 GraphQL API 响应中测试数据
- css - CSS:有序列表中编号的垂直位置
- excel - 在两个特定工作表之间按字母顺序插入新工作表
- ssh - ssh permission denied when prefixing with ssh protocol
- azure - How to redirect traffic hosted on an azure endpoint (DNS/static IP) to different external IP address
- download - ionic4/Angular7 - Property 'dataDirectory' does not exist on type 'File'
- mysql - 我无法通过 PHPMyAdmin 导入数据库
- android - Android Pie 中是否存在用于 NFC 标签连接的错误?