search

Home  >  Q&A  >  body text

c++ - 函数返回char类型数组,调用 函数后如何接收值?

我现在刚在学C语言,今天想要实现一个功能:

用C语言读取一个文件的指定行,(如读取a.log文件的3--5行),现在实现了读取函数, 但在main函数调用时不知道怎么接收返回的值。

代码如下:

#include <stdio.h>
/* 
读取a.log中第3行到第5行的内容 

*/

#define MAXLIN 100
#define FILENAME "a.log"
 

char* getFileRows(char* filename,int start_line, int end_line);


int main()
{  
    
    getFileRows(FILENAME,3,5);

  /*
  getFileRows 函数返回的是 data[3][100] 这种的char类型数组。
  getFileRows 函数返回的是char类型的数组, 我这里应该怎么定义变量,来接收返回值呢? 
  */
 
  
     

 return 1;    
}

/*
 读取文件, 读取 start_line 到 end_line 行之间的内容
*/
char* getFileRows(char* logfile,int start_line, int end_line)
{ 
    int k=0,i = 0 ; 
    int pos = 1;
    char c; 
    int line = end_line - start_line;
    char data[line][MAXLIN];
    FILE* fp = fopen(logfile,"r");
    
    if(fp == NULL){
         printf("FILE OPEN ERROR");
         getchar();
         exit(1);
    }  
    while(i<start_line && !feof(fp)){ 
       fseek(fp,pos,SEEK_SET);
       while( (c=fgetc(fp)) != NULL){
                   pos++; 
                   if(c == '\n'){ 
                    break;
                 } 
         } 
        i++;  
   } 
   
  for(k=0;k<=line;k++){
        fgets(data[k],MAXLIN,fp);   
  }   
   return data;   
}
高洛峰高洛峰2809 days ago779

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 15:26:13

    Do not directly return the array declared inside the function. The stack will be recycled after the function exits. Or just like you used fgets, define the buffer outside the function, and then pass the buffer and length as function parameters. Or you can malloc a piece of char memory inside the function, write the tail 0 internally, and then return this address, and free it externally after use. Of course, this is a bad programming habit. You can encapsulate a destroy function, After use, pass the returned address as a parameter and release all the memory requested in the get function.

    reply
    0
  • 阿神

    阿神2017-04-17 15:26:13

    Your data is on the stack, and the stack will be recycled when the function returns. Accessing the data will cause unpredictable errors.

    Declare data in the main function, and then pass the data to getFileRows through parameters to receive the data.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:26:13

    A data array should be declared outside the function, the array address and array length should be passed into the function as parameters, and the data should be read and saved inside the function (the array name is used as a pointer, and the array is no longer declared inside the function)

    reply
    0
  • Cancelreply