开发者

Returning Arrays C++

I can't seem to understand why this won't work.

Global variable:

int genericSet[] = {1,2,3,4};

int main()...
开发者_运维知识库
int* function() {
    return &genericSet;
}

Why would it give me an error while trying to return this array? Is it because it's a global variable, if so why would that matter? How would I normally return a statically declared array? I realize this is extra work returning a global variable, but does it actually prevent this? I just used it as a place holder and kept getting an error.


Your function type doesn't match the return type. Your function is int*, but what you're returning is of type int**.


I have no idea why everyone is answering that &genericSet is an int**; it isn't. To clarify:

int genericSet[] = {1,2,3,4};
typedef int (*ArrayPtr)[4];
int* f1() { return genericSet; }
ArrayPtr f2() { return &genericSet; }


You return the address of a variable, which is an array.

It can be seen as returning a pointer to a pointer. You do not need the &, simply return the array.

So either:

int ** function()
{
    return ( int ** )&genericSet;
}

or:

int * function()
{
    return genericSet;
}


Just return genericSet without the & in front of it. It's already a pointer type by virtue of it having [] as part of its type.

Pointer/array similarities in C++ are important to understand, so I'd recommend you read up on that as part of your journey through the language.


genericSet itself is already an int *; &genericSet is an int **, a pointer to pointer to int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜