C语言字符指针

字符型数组和指针

第三行 指针变量p 保存的是 后面字符串常量的首字符地址 H的地址

不能用 s = “Hello”; 来进行赋值,数组s不能被整体赋值

p = s;代表指针变量p里面存放的是s数组的首元素s[0]的地址

strlen(p) = 12。 sizeof(p) = 8。 sizeof(s) = 100, strlen(s) = 5。

在函数内定义的 指针 也是存在栈区, 当指针指向字符串常量时,指针不能修改,

字符串常量存在字符串常量区。

指针变量前的 const 是指不能修改指针指向的变量, 而不是指针本身的存的地址不能被修改,即 *p不能被修改, p可以被修改。

整形变量前的 const 是指 i为只读变量,不能修改。

int * const p; 指针p存的地址不能修改,p存放的地址指向的变量可以修改,const修饰的p。

const 要不要加 取决需不需要修改传过来的参数的内容。

stratic 修饰局部变量时 是将局部变量的动态生存期变为静态生存期,但是使用范围还是局部,

修饰全局变量时,是限制该变量只能在本文件使用,不能跨文件使用。

void *万能指针

void *p; 定义了一个万能指针P,p指针可以存任何类型的地址。

万能指针不能进行 指针运算,即 *p = 1.2; 会发生编程报错。

代码练习:

e1.自己写函数实现字符数组的复制,连接,比较,打印,写出从一个长字符串中找到与一个小字符串,并返回第一次相同的下标。

#include<stdio.h>

void myPuts(const char *s)
{
	while(*s)
	{
		putchar(*s++);
	}
	putchar('\n');
	return ;
}

int mystrlen(const char *s)
{
	if(*s == '\0')
	{
		return 0;
	}
	else
	{
		return mystrlen(s+1) + 1;
	}
	
//	while(*s++)
//	{
//		sum += 1;
//	}
//	return sum;

}

char *mystrcpy(char *des , const char *src)
{
	char *ret = des;
	while(*src)
	{
		*des++ = *src++;
//		++des;
//		++src;
	}
	*des = 0;
	return ret;
}

char *mystrncpy(char *des, const char*src, size_t n)
{
	char *ret = des;
	while(*src && n--)
	{
		*des++ = *src++;
	}
	*des = 0;
	return ret;
}

char *mystrcat(char *des, const char *src)
{
	char *ret = des;
	while (*des)
	{
		++des;
	}
	while(*src)
	{
		*des = *src;
		++des;
		++src;
	}
	*des = 0;
	return ret;
}

char *mystrncat(char *des, const char *src, size_t n)
{
	char *ret = des;
	while (*des)
	{
		++des;
	}
	while(*src && n-- > 0)
	{
		*des = *src;
		++des;
		++src;
	}
	*des = 0;
	return ret;
}

int mystrcmp(const char *s1, const char *s2)
{
	while(*s1 == *s2 && s1 && s2)
	{
		++s1;
		++s2;
	}
	int ret = *s1 - *s2;

}


int mystrncmp(const char *s1, const char *s2, size_t n)
{
	while(*s1 == *s2 && s1 && s2 && --n)
	{
		++s1;
		++s2;
	}
	int ret = *s1 - *s2;

}

int strFind(const char *s, const char *sub)
{
	int i = 0;
	for (i = 0; i <= mystrlen(s) - mystrlen(sub); ++i)
	{
		if(mystrncmp(s+i,sub,mystrlen(sub)) == 0)
		{
			return i;
		}
	}
	return -1;
}


int main(int argc, const char *argv[])
{
	char s1[100] = "hello world china amercia";
	char s2[100] = "cia";
	int ret = strFind(s1,s2);
	if(ret >= 0)
	{
		printf("%d\n",ret);
	}
	else
	{
		printf("not found\n");
	}
    return 0;
 }

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值