首页 > 解决方案 > 为什么我不能迭代在 C 中返回的字符串?

问题描述

当我在这样的 void 函数中遍历字符串时,它不会给我任何问题,而是遍历我输入的字符串。

#include <stdio.h>
#include <string.h>
void iter_string (void){

   char source[30];
   scanf(" %[^\n]s",source );;
   int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
   for (int i = 0; i < length; i++)
   {

      printf("%c\n", source[i]);

   }
   //return 0;
}

int main(void)
{
  iter_string();
  return 0;
}

但是,当我修改函数以返回输入值并将其存储在主函数中的值中时,就会出现问题。它给了我一个称为分段错误的错误:11。为什么是这样?

const char* iter_string (void){

   char source[30];
   scanf(" %[^\n]s",source );;
   int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
   for (int i = 0; i < length; i++)
   {

      printf("%c\n", source[i]);

   }
   return *source;
}

int main(void)
{
  char author[30];

  strcpy(author,iter_string());
  printf("%s\n",author );
  return 0;
}

标签: arrayscpointers

解决方案


因为您正在返回对函数执行完成后不再存在的内存的引用。

如果要返回该指针,则必须以动态方式声明它:

char *source = malloc(30);

// Do your processing here...
return source; // No asterisk here

然后在 main 中,要对函数内部分配的内存进行适当的清理,您应该释放您 malloc 的内容:

char * temp = iter_string();
strcpy(author, temp);
free(temp);

其他替代方法是将作者作为参数传递并在内部进行更改。


推荐阅读