鱼C论坛

 找回密码
 立即注册
查看: 1623|回复: 2

字符数组作为函数返回值如何承接

[复制链接]
发表于 2022-2-23 17:39:36 | 显示全部楼层 |阅读模式
20鱼币
  1. #include<stdio.h>
  2. #include<string.h>

  3. char reverse(char a[])//定义一个字符反转函数,希望返回是和a反转的字符数组
  4. {
  5.         char b[100];
  6.         int i = 0;
  7.         int j = 0;
  8.         while (a[i])
  9.         {
  10.                 i++;
  11.         }
  12.         i = i - 1;
  13.         while ((i+1)!= 0)
  14.         {
  15.                 b[j] = a[i];
  16.                 j++;
  17.                 i--;
  18.         }
  19.         return &b;
  20. }

  21. int main()
  22. {
  23.         char a[100];
  24.         gets(a);
  25.         char *b;
  26.         b=reverse(a);
  27.         puts(b);}
复制代码

不知道用什么去承接函数的返回值,运行会有越界提示

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-2-23 17:45:10 | 显示全部楼层
找到原因了。来分享一下,char定义的函数返回值是字符,而char*定义的函数返回值才是字符指针,一开始函数用char来定义,虽然返回值b是一个字符指针,但函数只能返回数组,把一个字符赋给字符指针出现了越界问题
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-2-23 22:28:31 | 显示全部楼层


既然你已经 #include <string.h>
就用 strlen来获取字符串长度就好啦,可以省去你用while跑一遍统计

  1. #include <stdio.h>
  2. #include <string.h>

  3. int main(){
  4. char a[100] = "hello world";
  5. printf("original string is " %s ".\n",a);

  6. int left = 0, right = strlen(a) - 1;
  7. while(left < right){
  8.     char ctemp = a[left];
  9.     a[left] = a[right];
  10.     a[right] = ctemp;
  11.     left++;
  12.     right--;
  13. }
  14. printf("converted string is " %s ".\n",a);

  15. return 0;
  16. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-25 02:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表