#之前看到一个用指针操作把两个字符数组拼接起来的问题,下面是我的代码,但是报错了,我不太懂指针操作。
我的代码如下:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter the first string:\n");
scanf("%s", str1);
printf("Enter the second string:\n");
scanf("%s", str2);
// 指向 str1 末尾的指针
char *ptr = str1 + strlen(str1);
// 将 str2 连接到 str1 后面
while (*str2 != '\0') {
*ptr = *str2;
ptr++;
str2++;
}
*ptr = '\0';
printf("The combined string is: %s\n", str1);
return 0;
}
报错信息:
在str2++;这一行,报错信息:需要作为增量操作数的左值
我看到的原帖子的可以运行的代码如下:
#include <stdio.h>
void mystrcat(char *s1, char *s2) {
while (*s1)
s1++;
while (*s2) {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char s1[100];
char s2[100];
scanf("%s", s1);
scanf("%s", s2);
mystrcat(s1, s2);
printf("%s", s1);
return 0;
}
有人帮我解释一下我的那一行为什么报错吗,该怎么改呢?