Reputation: 683
I've a function which takes an int *
as argument but I've an int[]
, how can I pass the argument to it?
I used this method but i think it's not efficient:
void myFunc(int * ar);
...
int main(){
int ar[]={1,2,3,4,5};
int *ar2=new int [5];
memcpy(ar2,ar,5*sizeof(int));
myFunc(ar2);
}
passing array itself causes compilation error.
Upvotes: 0
Views: 3732
Reputation: 1103
you can Pass int[]
to function with argument int *
,but the function can not know the length of the array.so you should add one more argument to the function,like: myFunc(int *arr,int length)
Upvotes: 1
Reputation: 41
You can do that by just passing the name of the array i.e. ar.
The name of the array is actually the address of the first element of the array, hence passing it in a function that takes an argument of type
int *ar
is the way to do it!
myFun(ar)
will do the job just fine;
Upvotes: 0
Reputation: 180
an array can be converted into a pointer so you can pass the argument like this:
myFunc(ar2);
since ar2 is an array we can pass the array because the parameters in myFunc is pointer to an int which is ar2
heres how it works
#include <iostream>
#include <string.h>
using namespace std;
void myFunc(int *ar)
{
for (int i = 0; i != 5; ++i)
std::cout << *(ar + i ) << std::endl;
}
int main()
{
int ar[]={1,2,3,4,5};
int *ar2=new int [5];
memcpy(ar2,ar,5*sizeof(int));
myFunc(ar2);
delete ar2; /// dont forget to de allocate :)
return 0;
}
output
1
2
3
4
5
Upvotes: 0
Reputation: 7663
You can directly pass an int[] as an int* parameter. An array can be decayed into a pointer.
This code will compile:
void myFunc(int * ar);
...
int main(){
int ar[]={1,2,3,4,5};
myFunc(ar);
}
Upvotes: 3