栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

编写一个函数,实现两个字符串的比较.即自己写一个strcmp函数,函数原型为strcmp(char *p1,char *p2);

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

编写一个函数,实现两个字符串的比较.即自己写一个strcmp函数,函数原型为strcmp(char *p1,char *p2);

在解答这个题时遇到的问题,记录一下吧~

#include 

int main(void) {
    int strcmp1(char* p1, char* p2);
	char s1[100], s2[100];
	scanf("%s", s1);//不能写成s1="boy",s1[100]="boy"
	scanf("%s", s2);
	char* p1;
	char* p2;
	p1 = &s1[0];
	p2 = &s2[0];
	printf("%d", strcmp1(p1, p2));return 0;
}
int strcmp1(char* p1, char* p2) {
	int i = 0;
	while (*(p1 + i) == *(p2 + i)) {	
		if (*(p1 +i++) == ''){//先判断*(p1 +i) == '',再i++
            return 0;
        }
        
	}
	return (*(p1 + i) - *(p2 + i));
}

①写成s1="boy";

报错:Array type 'char[100]' is not assignableclang(typecheck_array_not_modifiable_lvalue)

原因:s1="boy";这里的s1是指针,赋值“boy”,出现指针混乱。

②写成s1[100]="boy";

报错:Array index 100 is past the end of the array (which contains 100 elements)clang(-Warray-bounds)

原因:这里的s1[100]是指一个字符,而数组的下标是从0开始的,s1[100]不存在,下标最大为99

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018449.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号