0

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);
}
1
  • 1
    You can't return a built-in array. Fortunately, you shouldn't even have a need for those anyway with std::array. Commented Jul 4, 2013 at 20:56

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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");
}

4 Comments

Why not return the vector instead?
@KonradRudolph Well, why not?
@KonradRudolph (maybe because some ancient compilers don't to copy elision and RVO.)
Thanks H2CO3. I used vector as the return type and it worked perfectly. :D
0
  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.

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.