简体   繁体   中英

How do I return a pointer to a struct from a function?

I am having trouble understanding why the compiler is giving me the following error:

level0.c: In function 'create_grid': level0.c:28:9: warning: return from incompatible pointer type [-Wincompatible-pointer-types] return grid;

I am trying to return a pointer to a struct that I created of type struct gridType in the function. That is also the type that the function expects to be returned.

The code for the function is:

struct gridType* create_grid(int length){

    char** array = malloc(length * sizeof(*array));
    for(int i = 0; i < length; i++){
        array[i] = malloc(length * sizeof(array));
    }   

    for(int i = 0; i < length; i++){
        for (int j = 0; j < length; j++){
            array[i][j] = '-';
        }   
    }   

    struct gridType{
        int length; 
        char** array;
    };

    struct gridType* grid = malloc(sizeof(struct gridType));

    grid->length = length;
    grid->array = array;

    return grid;
}

You can't define struct gridType inside your function and expect to be able to return it (for other people to see).

Type moving

struct gridType{
    int length; 
    char** array;
};

Outside (before) the function create_grid() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM