问题
如题
代码(用字符指针实现)
#include<stdio.h>
#include<string.h>
#define N 50
int main()
{
char str1[] = "Hello ";//待连接的字符串1
char str2[] = "World";//待连接的字符串2
char str3[N];//最后保存字符串连接结果的数组
char * p;//指向字符串单个字符的指针
int i = 0;//字符下标
//测试str3在没有初始化的情况下是否包含'\0'字符
if (strchr(str3, '\0') != NULL)
{
printf("字符串包含 null 字符\n");
}
else
{
printf("字符串不包含 null 字符\n");
}
p = str1;
while (*p != '\0')
{
str3[i] = *p++;
i++;
} //先把str1中的内容复制到str3中(指针指到字符串结束符'\0'为止)
p = str2;
while(*p != '\0')
{
str3[i] = *p++;
i++;
} //str1的内容复制完成后开始str2的复制
//printf("%d\n",strlen(str3));
//str3[strlen(str3)] = '\0';
p = str3;
while(*p != '\0')
{
printf("%c",*p++);//打印连接后的数组
}
return 0;
}
输出结果:
包含结束字符
Hello World
后来我发现我理解错题意了,我不应该再新增一个数组来存放,这样的话就类似于复制了,而不是连接两个数组,而应该直接在原数组的基础上再连接另一个数组。代码如下:
#include<stdio.h>
int main(){
char ch[100] = "welcome";//待连接的数组
char * p = "hello world";
int i = 0;//ch数组下标
while (*(ch+i) != '\0')
{
i++;
}//先把指针移到ch数组'\0'的位置,好做替换
while (*p != '\0')
{
*(ch+i) = *p;
i++;
p++;
}//把p指针指到的数据赋值给ch数组'\0'及以后的位置
*(ch+i) = *p;//把p指针指到的'\0'也赋值给ch数组
i = 0;
while(*(ch+i) != '\0')
{
printf("%c",*(ch+i));
i++;
}//打印整个数组
return 0;
}
输出结果:
welcomehello world
感悟
- 注意第一个打印结果大概率会是"Hello World",因为在声明str3时没有作初始化,所以这时候它的值在内存当中是不确定的,但是很大概率会包含’\0’
- 为了打印结果的完全正确性,需要对str3数组进行初始化,即char str3[] = “”
- 一定要仔细审题!!理解了题意再去想思路,不要太草率!!
- ch[i] = *(ch+i) 记得左边式子里的括号要加上!否则有歧义:具体见:
*ch+i 和 *(ch+i) 的区别