C++定义一个字符数组并初始化为"hello world!",编写程序逆序输出此字符数组。 字符数组中的数据前后交换,逆序放置。定义指针
时间: 2024-05-03 21:22:06 浏览: 13
来操作数组元素,具体实现代码如下:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "hello world!";
int len = strlen(str);
char* p = str;
char temp;
// 逆序交换字符
for (int i = 0; i < len / 2; i++) {
temp = *(p + i);
*(p + i) = *(p + len - i - 1);
*(p + len - i - 1) = temp;
}
printf("逆序输出字符数组: %s\n", str);
return 0;
}
```
相关问题
定义一个字符数组并初始化为"hello world!",编写程序逆序输出此字符数组。 字符数组中的数据前后交换,逆序放置。定义指针
char arr[] = "hello world!";
int len = strlen(arr);
char *p = arr + len - 1;
while (p >= arr) {
printf("%c", *p);
p--;
}
// 输出结果为: !dlrow olleh
c语言定义一个字符数组,输入字符串,再逆序输出
可以使用以下代码来实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100]; // 定义一个最大长度为100的字符数组
printf("请输入一个字符串:");
fgets(str, 100, stdin); // 从标准输入中读入一个字符串
int len = strlen(str); // 获取字符串的长度
printf("逆序输出字符串为:");
for (int i = len - 1; i >= 0; i--) { // 从字符串末尾开始遍历并输出
printf("%c", str[i]);
}
printf("\n");
return 0;
}
```
上述代码中,使用 `fgets()` 函数从标准输入中读入一个字符串,并存储在字符数组 `str` 中。然后使用 `strlen()` 函数获取字符串的长度,从字符串末尾开始遍历字符数组,并输出每个字符,最后换行。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)