C语言实现符合变量约束的MyStrlen及编译警告修复
需求与问题描述
需要编写C语言自定义函数MyStrlen,实现与标准库strlen()完全等价的字符串长度统计功能,附带严格约束:
- 函数内仅能使用两个变量:传入的形参变量、一个指向const char的const指针类型的变量,示例写法为
const char * const START = s1(s1为待统计长度的输入字符串) - 最终需同时调用
strlen和MyStrlen,对比二者返回值后输出结果
当前编译过程中触发两类警告:
MyStrlen内部触发:Value computed is not used- 大范围数据丢失警告:
'initializing': conversion from '__int64' to 'int', possible loss of data
已编写代码
自定义MyStrlen函数
//与strlen()功能等价的自定义函数: #include <stddef.h> size_t MyStrlen(const char *s1) { const char * const START = s1; //遍历字符串直到遇到空终止符'\0' while (*s1 != '\0') { *(s1++); } //计算两个指针的差值并返回该值 int Difference = s1 - START; return (int)Difference; }
主函数代码
#include <stdio.h> #include <string.h> size_t MyStrlen(const char *s1); const int STR_SIZE = 100; const int LENGTH = (STR_SIZE + 1); //为字符串末尾的空终止符'\0'预留空间 int main(void) { char s1[LENGTH]; printf("请输入任意空格分隔的字符串:"); //读取输入字符串并将换行符替换为空终止符'\0' fgets(s1,STR_SIZE,stdin); s1[strcspn(s1, "\n")] = '\0'; //分别调用标准库strlen与自定义的MyStrlen函数 int Macro_value = strlen(s1); int My_value = MyStrlen(s1); //输出字符串及两个函数返回的长度值以做对比 printf("\nstrlen(\"%s\") 返回值 %d\n" "MyStrlen(\"%s\") 返回值 %d\n", s1, Macro_value, s1, My_value); return 0; }
问题原因与修正方案
1. Value computed is not used警告修正
while循环内的*(s1++);属于冗余操作:指针自增的效果已经独立完成,对自增前地址的解引用结果没有被任何逻辑使用,因此触发警告。
直接将该行修改为s1++;即可,无需额外解引用。
该逻辑不会出现越界问题:while的判断条件为
*s1 != '\0',仅当当前位置不是空终止符时才会执行自增,遍历结束时指针恰好停在字符串末尾的\0位置,符合长度统计的逻辑。
2. 数据丢失警告修正
- 同类型指针做减法得到的结果类型为
ptrdiff_t,在64位系统上为与指针等宽的64位类型,强行转换为32位的int变量就会触发高位数据丢失的警告。 - 原代码中手动定义
int Difference存储差值,既违反了“仅使用两个变量”的约束,又触发类型转换问题,直接删除该定义行,返回指针差值即可:return s1 - START; - 主函数中存储
strlen、MyStrlen返回值的变量类型从int改为size_t(与两个函数的返回类型完全匹配),输出时对应的格式符从%d改为%zu(适配size_t类型的跨平台格式符),即可消除全部类型转换警告。
修正后完整代码
符合约束的MyStrlen函数
(函数内仅包含形参s1、const char * const START两个变量,完全满足题设约束)
#include <stddef.h> size_t MyStrlen(const char *s1) { const char * const START = s1; while (*s1 != '\0') { s1++; } return s1 - START; }
修正后主函数
#include <stdio.h> #include <string.h> size_t MyStrlen(const char *s1); const int STR_SIZE = 100; const int LENGTH = (STR_SIZE + 1); //为字符串末尾的空终止符'\0'预留空间 int main(void) { char s1[LENGTH]; printf("请输入任意空格分隔的字符串:"); fgets(s1,STR_SIZE,stdin); s1[strcspn(s1, "\n")] = '\0'; size_t Macro_value = strlen(s1); size_t My_value = MyStrlen(s1); printf("\nstrlen(\"%s\") 返回值 %zu\n" "MyStrlen(\"%s\") 返回值 %zu\n", s1, Macro_value, s1, My_value); return 0; }
内容的提问来源于stack exchange,提问作者TIN_MAN_025
相关产品推荐
相关产品推荐

