【问题标题】:Cannot convert ‘char (*)[1024]’ to ‘char*’ in return [duplicate]无法将“char (*)[1024]”转换为“char*”作为回报[重复]
【发布时间】:2016-05-05 18:55:23
【问题描述】:

我想逐行读取一个简单的文件并将内容保存到一个数组中。如果我编译源代码,我会收到此错误:

test.C: In function ‘char* read_file(int, int, const char*)’:
test.C:14:11: error: cannot convert ‘char (*)[1024]’ to ‘char*’ in return
    return words;
           ^

这是什么意思?为什么我不能返回二维数组的指针?这是源代码。

#include <stdio.h>
#include <string.h>

char * read_file(int buf, int size, const char *fname){
   char words[size][buf];
   FILE *fptr = NULL; 
   int idx = 0;

   fptr = fopen(fname, "r");
   while(fgets(words[idx], buf, fptr)) {
      words[idx][strlen(words[idx]) - 1] = '\0';
      idx++;
   }
   return words;
}

int main(void) {
   char * words;
   words = read_file(1024, 100, "text.txt");
   int i;
   for(i = 0; i < 100; ++i)
        printf("%s\n", words[i]);
}

【问题讨论】:

  • 'char words[size][buf];' - 自动存储,>GONE
  • 无论转换错误如何,您都不想做这似乎正在尝试的事情。 Lashane 评论中的链接很重要。

标签: c readfile


【解决方案1】:

你实际上有两个问题:第一个是关于错误的。 char 的数组数组与指向 char 的指针不同。随着数组衰减为指针,char 数组的数组等效于指向char 数组的指针,或者在您的特定情况下为char (*)[buf]

第二个问题更糟糕,那就是你试图返回一个指向局部变量的指针。一旦函数返回,局部变量就会超出范围,并且基本上不再存在。所以一旦函数返回,指针就不再有效。

由于您使用可变长度数组,您拥有的一种解决方案是动态分配数组,作为指向char 的指针的指针,即char **,并返回它。另一种解决方案是将数组作为参数传递。


在我看来,最简单的解决方案是在 main 函数中声明数组并将其传递给函数,这样您就不必为指针和动态分配而烦恼,尤其是稍后释放内存。

类似这样的:

#define STRING_COUNT  100    // Number of strings
#define STRING_SIZE   1024   // Size of each string

// Open and read the file, returns the number of "words" read
size_t read_file(const char *filename, char (*words)[STRING_SIZE])
{
    // Implement the function...
    // Don't forget to return the number of "words", actually lines, you read
}

int main(void)
{
    char words[STRING_COUNT][STRING_SIZE];
    size_t number_words = read_file("test.txt", words);

    // Use the "words" here...
    ...

    return 0;
}

【讨论】:

  • 您好,谢谢您的回答,能给我一个简短的例子吗?
  • @Sam 添加了简单(不完整)示例,展示了如何将数组作为参数传入。
  • 谢谢,我去看看。
猜你喜欢
  • 2022-01-10
  • 2012-09-03
  • 2016-07-20
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多