返回在 c 中保存字符串的变量并将其打印出来

问题描述

我有这样的功能

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

return string;
}

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

它打印NULL,有什么修复吗?谢谢

解决方法

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

In function ‘string’:
warning: function returns address of local variable [-Wreturn-local-addr]
 return string;
        ^~~~~~

你有两个选择:

  • 将指向 char 数组的指针传递给您的函数(字符串)或
  • malloc 返回字符串(string_from_file)
#include <stdio.h>
#include <string.h> // for memset

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

char *string_from_file(FILE *ifp)
{
    char *s = malloc(256);
    fscanf(ifp,s);
    return s;
}


int main(int ac,char **av)
{
    FILE *ifp = fopen(av[1],"r");
    
    // using ptr:
    char s[256];
    memset(s,256); // fill s with '\0'
    string(ifp,s);
    printf("%s\n",s);
    
    // using malloc:
    printf("%s\n",string_from_file(ifp));
}

请注意,它只会让您了解程序的前几个字,如果有帮助,请告诉我

注意:我没有倒回文件指针,所以上面的例子将打印前两个字。

,

您的“char string[]”是在您的字符串函数中创建的局部变量,但在 C 局部变量在函数执行后仍然不可用(用于该变量的内存可自由用于其他程序);

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

#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;
}