用指针实现C语言程序:输入1个字符串,把该字符串的前3个字母移动到最后,输出变换后的字符串
时间: 2024-02-28 20:55:10 浏览: 35
好的,以下是代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
char *p = str;
char temp[3];
for (int i = 0; i < 3; i++) {
temp[i] = *p;
p++;
}
for (int i = 0; i < len - 3; i++) {
*p = *(p + 3);
p++;
}
for (int i = 0; i < 3; i++) {
*p = temp[i];
p++;
}
printf("变换后的字符串为:%s\n", str);
return 0;
}
```
解释一下:
1. 先输入一个字符串,并获取字符串长度。
2. 定义一个指针 p 指向字符串的首地址。
3. 定义一个临时数组 temp 存储前三个字符。
4. 通过指针 p,将前三个字符存储到临时数组 temp 中。
5. 通过指针 p,将字符串的第四个字符开始的所有字符向前移动三个位置。
6. 通过指针 p,将临时数组 temp 中的三个字符添加到字符串的末尾。
7. 输出变换后的字符串。
注意:在实现中,指针操作需要非常小心,特别是在修改指针指向的内存地址时,一定要确保不会越界或者误操作。