简体   繁体   中英

Function declaration error - returning an array of pointers

This is the error for the function declaration statement for retstr.

"prog.cpp:5: error: expected unqualified-id before '[' token prog.cpp:5: error: expected initializer before '[' token"

Here is the code:

#include<stdio.h>
#include<math.h>
int n;
char *[] retstr(int k)
{
        char* ans[10];
        return(ans);
}

First and foremost, if you wanted to declare a function that returns a raw array of 10 char * pointers, the proper syntax would be

char *retstr(int k)[10]
{
  char* ans[10];
  return ans;
}

However, this solves nothing since neither in C nor in C++ functions are allowed to return arrays directly. So, even with proper syntax a direct attempt to return a raw array will not work.

Choose a different approach out of the ones already suggested in other answers.

char *[] is not a type. It's a syntax error. What you probably wanted instead is

char **function()
{
}

but then, again, you are returning an automatic array which will invoke undefined behavior. Why not make your function fill a vector of strings instead?

void function(std::vector<std::string> &v)
{
    v.push_back("foo");
    v.push_back("bar");
}
  1. Returning an array is not something you can do in C++.

  2. Your function actually returns a pointer to the first element of ans , which is also bad news, since that array is declared on the stack and goes out of scope as soon as the function returns.

The right thing to do would be to pick an appropriate data structure from the C++ standard library and use that. If for some reason you're set on fundamental types, you'll need to come up with a different solution - perhaps allocating the array dynamically inside your function and returning a pointer to it, for example.

Try this:

#include<stdio.h>
#include<math.h>
int n;
char ** retstr(int k)
{
    char** ans = (char**) malloc(10 * sizeof(char*));
    return ans;
}

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