Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a char pointer in C

I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below

char* ListFiles(){
    FILE *fp;
    char file[30];
    char *f;
    if((fp=fopen("list","r"))==NULL)  
    {
        ...
    }
    while (!feof(fp))
    {
        fgets(file,50,fp);
    }
    fclose(fp);
    f=file;
    printf("%s",f); //get display!!!
    return f;
}
int main(){
      char *files;
      ...
      ...
      files=ListFiles();
      printf("%s",files); //nothing display!!
      sent();
}

However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work.

like image 708
panda Avatar asked Apr 12 '12 20:04

panda


People also ask

Can you return a pointer in C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

What does a char * function return?

The result of the CHAR function is a fixed-length character string. If the first argument can be null, the result can be null. If the first argument is null, the result is the null value. The first argument cannot be an XML value.

Can we return char array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Which function has a return type as char pointer?

4. Which function has a return type as char pointer? Explanation: None.


2 Answers

Follow George Skoptsov recommendations. But If you don't have the strdup() function,then use this:

char* strdup(const char* org)
{
    if(org == NULL) return NULL;

    char* newstr = malloc(strlen(org)+1);
    char* p;

    if(newstr == NULL) return NULL;

    p = newstr;

    while(*org) *p++ = *org++; /* copy the string. */
    return newstr;
}

And then:

#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */

/* do something... */

char* ListFiles() {
        /* .... */ 
         return strdup(f);
}

Or instead of char file[30]; do a dynamic memory allocation: char* file = malloc(30); then you can do return f; and it will work fine because f now is not a pointer to a local variable.

like image 106
Jack Avatar answered Sep 24 '22 07:09

Jack


What you're doing is returning a pointer to a local variable, which used to be allocated on stack.

Change your return statement to

return strdup(file);
like image 22
George Skoptsov Avatar answered Sep 23 '22 07:09

George Skoptsov