简体   繁体   English

如何从函数返回指向结构的指针?

[英]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; level0.c:在函数“create_grid”中:level0.c:28:9:警告:从不兼容的指针类型返回 [-Wincompatible-pointer-types] 返回网格;

I am trying to return a pointer to a struct that I created of type struct gridType in the function.我试图返回一个指向我在函数中创建的 struct gridType 类型的结构的指针。 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).您不能在函数中定义struct gridType并期望能够返回它(供其他人查看)。

Type moving类型移动

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

Outside (before) the function create_grid() .在函数create_grid()之外(之前create_grid()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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