I'm just trying to return a char array from my function. I read quite a few posts and people were just suggesting to return char*. The compiler does let me use char* as a return type, but I want to return an array, not a pointer to it. This is what my function looks like:
char IsValid(char num[]) {
char newNum[101];
// do stuff
return newNum;
}
It seems that the return type does match the function type. They are both char. What's going on?
CodePudding user response:
The return type of a function cannot be an array. Since we are here, the num
parameter of your function is not an array, it's a pointer.
Anyway in C you shouldn't use C arrays. Use std::array
or std::vector
. Those can be parameter types and return types.
CodePudding user response:
char IsValid(char num[]) {
char newNum[101];
// do stuff
return newNum;
}
Arrays sometimes "decay" into pointers (meaning they turn into pointers and have to be treated as such). So to make this function capable of returning it, you'd need to set the return value as a char pointer (char*
), so that'd look like this:
char* IsValid(char num[])
Also, you can't have a parameter of type char[], because arrays are just pointers with constant sizes, so you'd need to further change the function to: (THIS IS FALSE INFORMATION, YOU CAN HAVE PARAMETERS OF TYPE type[]
AND I AM SORRY FOR THE MISTAKE).
Then you can do something like this:
char* IsValid(char num[]) {
static char newArr[100];
// that static keyword, in this case
// makes our new array act as if it was a global variable
// do stuff
return newArr;
}
int main() {
char arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char* return_arr = IsValid(arr);
}
More info about the static keyword
That being said, what bolov has said is correct. For arrays like this, it's better to use the standard library's container std::array for dealing with arrays of static (unchanging) sizes, or std::vector for arrays with dynamic sizing.
I wish you luck on your C journey!
CodePudding user response:
Your function must have a char pointer as argument and you can edit the array using the pointer variable; do this:
void IsValid(char* num) {
char newNum[101];
// do stuff
num[] = newNum[];
}