簡體   English   中英

返回變量在 c 中保存一個字符串並將其打印出來

[英]Returning Variable holding a string in c and printing it out

我有一個 function 像這樣

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 數組的指針傳遞給您的 function (字符串)或
  • 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, "%255s", s);
    return s;
}


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

請注意,它只會讓您了解程序的前幾句話,讓我知道它是否有幫助

注意:我沒有倒回文件指針,所以上面的例子會打印前兩個單詞。

Your "char string[]" is a local variable create in your string function, but in C local variable are not stilling availlable after the function was executed (the memory used for this variable is free to be available for an other program);

您可以保留 memory 供您使用 malloc function 進行編程,但請注意永遠不要忘記釋放分配的 ZCD691B4957F08CD21!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM