Search code examples
carraysreturn

Returning a pointer to a char array inside a struct in C?


I have the following struct in the header file:

static FILINFO fno;

Which looks like so:

typedef struct {
DWORD   fsize;      /* File size */
WORD    fdate;      /* Last modified date */
WORD    ftime;      /* Last modified time */
BYTE    fattrib;    /* Attribute */
char    fname[13];  /* File name */
} FILINFO;

Now I would like a certain function to return a pointer to fname[] which should be possible since the struct is defined static. Here is my function:

char* get_open_file_name (void)
{
    return fno.fname;
}

I'm calling this function from main like so:

char* temp;

int main (void)
{
    intialize_sd_card ();
    ...
    ...
    temp = get_open_file_name();

This results in conflicting types error message. However if I try to call it like so:

char* temp = get_open_file_name();

It works. What am I missing here?

EDIT: Here is the actual error msg I'm getting from GCC

Severity    Code    Description Project File    Line
Warning     assignment makes integer from pointer without a cast

Solution

  • Just a wild guess, but could something like this be at play here?

    #include <stdio.h>
    
    typedef struct {
        char fname[4];
    } FILINFO;
    
    static FILINFO fno;
    
    char* temp;
    
    char* get_open_file_name(void) {
        return fno.fname;
    }
    
    int main(void) {
        fno.fname[0] = 'L';
        fno.fname[1] = 'o';
        int temp; //my awesome hidden debug value, with regards, previous dev
        fno.fname[2] = 'l';
        fno.fname[3] = '\0';
        if(1 /*or whatever*/) {
            temp = get_open_file_name();
            printf("%s\n", temp);
        }
        return 0;
    }
    

    Owing to local-scope visibility rules, this frankenstein can be legal - that up to the point where the char pointer is to be casted to an integer, of course. Then if You replace temp = get_open_file_name(); with char* temp = get_open_file_name();, it will work fine.

    Once the offending debug value is gone, the following compiles and runs flawlessly, using GCC 9.2.0 with -s -O3 -std=c99 -pedantic -Wall -Wextra:

    #include <stdio.h>
    
    typedef struct {
        char fname[4];
    } FILINFO;
    
    static FILINFO fno;
    
    char* temp;
    
    char* get_open_file_name(void) {
        return fno.fname;
    }
    
    int main(void) {
        fno.fname[0] = 'L';
        fno.fname[1] = 'o';
        fno.fname[2] = 'l';
        fno.fname[3] = '\0';
        temp = get_open_file_name();
        printf("%s\n", temp);
        return 0;
    }