I want to create an array while passing it to a function, like we can do in Java or Python. For example:
class HelloWorld {
public static void main(String[] args) {
example(new int[]{1,2,3}); // Like this
}
static void example(int[] a){
System.out.print(a[0]);
}
}
or in python
def fun(x):
print(x[0])
fun((1, 2, 3)) #Like this
When I try to do something like this in C++ I get an error
void example(int a[]){
cout<<a[0]<<endl;
}
int main() {
// Write C++ code here
cout << "Hello world!"<<endl;
example(new int(3){0, 1, 2});
return 0;
}
This gives the error
error: expected ')' before '{' token
or
void example(int a[]){
cout<<a[0]<<endl;
}
int main() {
// Write C++ code here
cout << "Hello world!"<<endl;
example({0, 1, 2});
return 0;
}
Here the compiler takes the array {0, 1, 2}
as an initializer list.
error: cannot convert '' to 'int*'
I'd like if there is some way of achieving a function call similar to the 2nd attempt.
function({1, 2, 3, 4}); //An array of any size
I tried searching for it but wasn't able to find a solution that fits the bill. Any and all help is really appreciated and I thank everyone in advance.