arrays - 为什么我不能迭代在 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;
}
解决方案
因为您正在返回对函数执行完成后不再存在的内存的引用。
如果要返回该指针,则必须以动态方式声明它:
char *source = malloc(30);
// Do your processing here...
return source; // No asterisk here
然后在 main 中,要对函数内部分配的内存进行适当的清理,您应该释放您 malloc 的内容:
char * temp = iter_string();
strcpy(author, temp);
free(temp);
其他替代方法是将作者作为参数传递并在内部进行更改。
推荐阅读
- javascript - Vue JS如何绑定onChange事件来改变input中的值
- converse.js - conversejs:用户配置文件未在设备上更新
- typescript - TS2749:“XXX”指的是一个值,但在这里被用作一个类型。您的意思是“typeof XXX”吗?
- google-apps-script - 如何将两个电子表格中的数据与 appscript 进行比较?
- postgresql - PostgreSQL RLS 未按预期应用
- d3.js - d3.select 不是函数,但 d3 已导入(* as d3)
- matlab - 如何显示两个符号矩阵之间的相等性?
- pandoc - Pandoc citeproc 参考书目条目排序遵循 bib 文件中的条目顺序
- javascript - 如何查询不同值包含部分给定字符串的 Firestore?
- node.js - 请求正文中的 _doc