我试图让我的函数返回一个指向结构的指针,但编译器一直告诉我我正在返回一个不兼容的指针类型。
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;
}
我得到的错误是:
error: incompatible pointer types returning 'struct Array *' from a function with result type 'struct Array *' return Array;
我不明白为什么会这样说。我返回的值与指定的值不一样吗?任何帮助将不胜感激。
最佳答案
你已经在函数中声明了结构数组
将结构移到函数外以使其工作
结构的作用域在函数内,不在函数外
关于c - 错误返回不兼容指针不兼容 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275980/