Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回c中包含字符串的变量并将其打印出来_C_String - Fatal编程技术网

返回c中包含字符串的变量并将其打印出来

返回c中包含字符串的变量并将其打印出来,c,string,C,String,我有一个这样的函数 char *string(FILE *ifp) { char string[256]; fscanf(ifp, "%s", string); return string; } int main() { ....... printf("%s", string(ifp)); } 它打印的是空的,有修正吗?谢谢您正在返回一个本地地址,您应该通过查看警告来捕获该地址 In function ‘string’: warning: funct

我有一个这样的函数

char *string(FILE *ifp)
{
char string[256];
fscanf(ifp, "%s", string);

return string;
}

int main()
{
.......
printf("%s", string(ifp));
}

它打印的是空的,有修正吗?谢谢

您正在返回一个本地地址,您应该通过查看警告来捕获该地址

In function ‘string’:
warning: function returns address of local variable [-Wreturn-local-addr]
 return string;
        ^~~~~~
你有两个选择:

  • 将指向char数组的指针传递给函数(字符串)或
  • Malloc返回字符串(来自\u文件的字符串\u)
#包括
#包含//for memset
字符*字符串(文件*ifp,字符s[256])
{
fscanf(ifp,“%255s”,s);
}
来自_文件的char*string_(文件*ifp)
{
char*s=malloc(256);
fscanf(ifp,“%255s”,s);
返回s;
}
内部主(内部ac,字符**av)
{
文件*ifp=fopen(av[1],“r”);
//使用ptr:
chars[256];
memset(s,0,256);//用'\0'填充s
字符串(ifp,s);
printf(“%s\n”,s);
//使用malloc:
printf(“%s\n”,来自_文件(ifp)的字符串_);
}
请注意,它只会让你的程序的前几个字,让我知道它是否有帮助

注意:我没有倒带文件指针,因此上面的示例将打印前两个单词。

您的“char string[]”是在string函数中创建的局部变量,但在C中,局部变量在函数执行后不仍然可用(用于此变量的内存可供其他程序使用)

您可以使用malloc函数为您的程序保留内存,但请注意不要忘记释放malloced内存

#include <stdlib.h>

char *get_file_content(FILE *ifp)
{
    char *string = malloc(sizeof(char) * 256);

    if (string == NULL)
        return NULL;    //don't continue if the malloc failed
    fscanf(ifp, "%s", string);
     return string;
}

int main(void)
{
    ...
    free(string);    //free memory you malloced
    return 0;
}

#包括
字符*获取文件内容(文件*ifp)
{
char*string=malloc(sizeof(char)*256);
if(字符串==NULL)
返回NULL;//如果malloc失败,则不继续
fscanf(ifp,“%s”,字符串);
返回字符串;
}
内部主(空)
{
...
释放(字符串);//释放内存
返回0;
}

您需要分配内存才能成功返回string@John这个指针数组的声明是char*string[256];没有意义。
char*string[256]-->
静态字符字符串[256]
char*string=malloc(256)@AntoninGAVREL怎么办?给我1分钟我正在编辑答案谢谢你修好了<代码>fscanf(ifp,“%s”,s)-不会
fscanf(ifp,“%255s”,s)更好,同时检查
fscanf
是的好点,我编辑了返回值@John如果它解决了您的问题,您可能会接受它作为答案:)在
malloc
中不需要
sizeof(char)
在malloc参数中使用
(sizeof(type)*nb_对象)
,这只是一个消除错误的良好使用许可证