English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How do I declare a function that returns char if the variable to be returned is declared char s[200]? I tried simply with char function_name(variables) but it says the types are incompatible.
Just to mention, I tried to declare the variable simply char s but then I get other errors.

2006-12-09 04:43:50 · 3 answers · asked by Laura 2 in Computers & Internet Programming & Design

3 answers

Return a char pointer, but be careful. I'm not sure how you're doing this, but there are some problems you can encounter.

char * myfunc()
{
char s[200];
return s;
}

This will return a pointer to s, which you can use like an array. But, since myfunc will go out of scope, s will no longer be available memory, and your pointer will be invalid. The best thing to do would be to pass in an array to use and manipulate that, or use the new operator to create a new array.

void myfunc(char [] s)
{
// do stuff to s;
}

char * myfunc()
{
char * s = new char[200];
return s;
}

2006-12-09 04:56:59 · answer #1 · answered by rons_brain 2 · 2 0

So, inside your function you have something like the following?
char myFunction(...)
{
char s[200];
...
return s;
}

So s is a character array containing 200 individual characters. If you just want to return the first one, you could try "return s[1]". If you want to actually return all of s, then you need to write your function a little differently. You'd want to make the caller of the function responsible for declaring the array, and have them pass in a pointer in the argument list. For example:
void MyFunction(variables, char *s, int size_of_s)
{
//make sure size_of_s is >= 200
//do what you need to do with s
//return nothing, or return the number of characters you put in s, or 0 for success and non-zero for errors.
}

2006-12-09 12:51:11 · answer #2 · answered by 14 Characters Left 2 · 0 0

you probably want to return an array of characters (rather than a character). To do so, you have to use:

char[ ] function_name(variables)

// Enjoy ;)

2006-12-09 13:30:18 · answer #3 · answered by Ahmad Nasser 2 · 0 0

fedest.com, questions and answers