我试图使函数返回一个指向结构的指针,但是编译器一直告诉我返回的指针类型不兼容。

struct Array *createArray( unsigned int array_size )
{
    struct Array
    {
        unsigned int size;
        int *a;
    };
    struct Array *Array; //creates pointer to struct and then allocates appropriate memory
    Array = malloc( sizeof( struct Array ) );
    if ( array_size > 0 )
    {
        Array->size = array_size;
        Array->a = malloc( array_size * sizeof( unsigned int ) ); // size of array dependent on array_size
        for ( int *counter = ( *Array ).a; counter < ( ( *Array ).a + array_size ); counter++ )
        {
            Array->a = 0; // initializes all array elements to zero
        }
        return Array;
    }
    //else
    //  return Array;
}

我得到的错误是:
错误:返回“struct Array*”的指针类型不兼容
从结果类型为“struct Array*”的函数
返回数组;
我不明白为什么它会这么说。我返回的值是否与指定的值相同?任何帮助都将不胜感激。

最佳答案

您已经在函数中声明了struct数组
将结构移到函数外部以使其工作
结构的作用域在函数中,而不是在外部

关于c - 返回不兼容指针不兼容C时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22275980/

10-12 12:54
查看更多