how to do it?
int[] func(int x); // doesn't work
[]int func(int x); // doesn't work
int[3] func(int x); // doesn't work
is there any solution?
I know that
int* func (int x);
but then I must use malloc and so on.
Printable View
how to do it?
int[] func(int x); // doesn't work
[]int func(int x); // doesn't work
int[3] func(int x); // doesn't work
is there any solution?
I know that
int* func (int x);
but then I must use malloc and so on.
The name of an array is just a pointer to the array, cell zero. You cannot return an array any other way in C other than by pointer.
Keep in mind that you cannot dynamicly create "arrays". You can allocate consecutive blocks of memory, which you can treat an array, but you don't actually do:
int array[][] = new array[x][y];
Also keep in mind that unless the array is static, there is no way to return an array other than to malloc memory for it. In which case, you just end up returning a pointer to allocated memory anyway.
The answer to your question:
int * myfunc( );
Return a pointer to allocated memory or to a static array inside the function.
Quzah.
You can use :
int* function(int x)
You do not have to use malloc. You can declare a local variable in the calling function and pass it to function. Then you do not even have to return it.
Here is an example:
You can return the int array this way, but as you can see it is not necessary to set Numbers = ChangeNumber(Numbers) because you are passing the address of the array.Code:int* ChangeNumber(int *Num){
int i = 0;
for(i=0;i<10;i++){
Num[i] = i;
}
return Num;
}
int main(void){
int Numbers[10] = {0};
ChangeNumber(Numbers);
return 0;
}
- Sean
thank you for answering but I have some questions more.
this code doesn't work.Code:int* ChangeNumber(int *Num){
int i = 0;
for(i=0;i<10;i++){
Num[i] = i;
}
return Num;
}
int main(void){
int Numbers[10] = {0};
ChangeNumber(Numbers);
return 0;
}
what I want to do is
Code:int* funk(int a[]){
blaa blaa blaa
do something
return array;
}
int main(int argc, char *argv[]){
int array1[10], array2[10];
array1=func(array2);
return 0;
}
[code][/code]tagged by Salem
thanks, know I know:)