一、前言
在实际开发中,特别是芯片开发中,例如智能传感器芯片,经常直接使用C语言指针数据类型来操作寄存器。那么字符串指针就是我们常见的操作。
C语言没有单独的字符串对象,它是通过数组的形式来表示字符串的:
#include
#include
int main(void)
{
char str[] = "hello world";
printf("%s",str);
printf("%c",str[1]);
}
上述字符串“hello world”共11个字符,加上结束字符“0”在内存中共12个字符。
二、通过字符指针引用字符串
#include
#include
int main(void)
{
char *str = "hello world";
printf("%s",str);
printf("%c",str[1]);
}
字符串拷贝示例:
#include
#include
int main(void)
{
char str_src[] = "hello world";
char str_desc[12],*p1,*p2;
p1 = str_src;
p2 = str_desc;
while(*p1!='0'){
p1++;
p2++;
*p2 = *p1;
}
*p2 = '0';
printf("The str_src is : %s",str_src);
printf("The str_desc is : %s",str_desc);
}
三、字符串传参
1、使用字符串的数组名传递参数
#include
#include
int main(void)
{
char s1[] = "hello world";
char s2[12];
copyString(s1,s2);
printf("s2 = %s",s2);
}
void copyString(char str_src[],char str_desc[]){
int i;
for(i = 0; str_src[i]!='0';i++){
str_desc[i] = str_src[i];
}
str_desc[i] = '0';
}
2、使用字符串指针变量
形式一:
#include
#include
int main(void)
{
char *s1 = "hello world";
char *s2 = (char *)malloc(12);
copyString(s1,s2);
printf("s2 = %s",s2);
}
void copyString(char str_src[],char str_desc[]){
int i;
for(i = 0; str_src[i]!='0';i++){
str_desc[i] = str_src[i];
}
str_desc[i] = '0';
}
形式二:
#include
#include
int main(void)
{
char *s1 = "hello world";
char *s2 = (char *)malloc(12);
copyString(s1,s2);
printf("s2 = %s",s2);
}
void copyString(char *str_src ,char* str_desc){
int i;
for(i = 0; str_src[i]!='0';i++){
str_desc[i] = str_src[i];
}
str_desc[i] = '0';
}
三、字符串拷贝函数copyString几种简写的总结
1、形式一
void copyString(char *str_src ,char* str_desc){
while(( *str_desc = *str_src)!='0'){
str_desc++;
str_src++;
}
}
2、形式二
void copyString(char *str_src ,char* str_desc){
while(( *str_desc++ = *str_src++)!='0');
}
3、形式三
void copyString(char *str_src ,char* str_desc){
while( *str_src != '0'){
*str_desc++ = *str_src++;
}
*str_desc = '0';
}
4、形式四
void copyString(char *str_src ,char* str_desc){
while( *str_desc++ = *str_src++);
}