hi
Can anyone tell me how can i return a array of three integers form a function;
will it workCode:int funtion() { int array[]={ 2,3,4 }; return array[];}
hi
Can anyone tell me how can i return a array of three integers form a function;
will it workCode:int funtion() { int array[]={ 2,3,4 }; return array[];}
You cannot return an array from a function. What is the purpose of this function? Depending on its purpose, you could say, assign to an array that is passed (as a pointer) to this function.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
This is the way you "return array". As laserlight said you return the pointer:
But keep in mind that this should be WRONG. You will be returning a local variable. I mean array is a local variable for function() so the memory is allocated when calling function() and freed when you leave function() so you cannot return it. If you wanted the above you would have to use malloc(). Or pass the array as a parameter to the function as this:Code:int funtion() { int array[]={ 2,3,4 }; return array; }
Generally there are no real arrays in C. Keep in mind that array[i] means *(array+i), thus saying the value of the memory that is shown by the pointer array plus i spaces of memory.Code:int funtion(int *array) { array[]={ 2,3,4 }; //not sure if this would work return array; }
Nope it wouldn't. That's an initializer list and can (as the name suggests) only be used at the initialization stage, i.e. when the variable is defined.Code:array[]={ 2,3,4 }; //not sure if this would work
QuantumPete
"No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
"Have you tried turning it off and on again?" - The IT Crowd
Nope, this would be wrong.Code:int funtion() { int array[]={ 2,3,4 }; return array; }
int[3] != int
So essentially, you are returning an incorrect type, as well as a local variable as you describe.
Also, when passing an array to a function, ALWAYS pass the array's size!
Code:void funtion(int* array, int size) { if (size < 3) /* ERROR: Too small buffer */; int array2[] = { 2, 3, 4 }; memcpy(array, array2, sizeof(array2)); }