0
How does this code function and what is "new int[2]"?
#include <iostream> using namespace std; int *fun(){ return new int[2]; } int fun (int *p){ delete []p; return 0; } void fun (int *p, int q){ p[q] *=2; } void fun (int *p,int q,int r){ p[q]=r; } int main() { int *v=fun(); fun(v,0,1); fun(v,1,2); fun(v,0); cout << v[1]+v[0]; fun(v); }
5 Réponses
+ 1
Bebida Roja do agree...at least delete nd allocate function should have different name
0
new int [2] would allocate memory for two int ... it's array and having two element assigned as point v...
fun(v,0,1) will be a function call and it set like v[0] = 1(array passes to function as reference and even though it is not returned, array v got updated)
fun(v,1,2) sets v[1]=2
fun(v,0) will call p[q] *=2 which is v[1]*=2 means v[0] = 2*1 = 2
as v[0] and v[1] both are 2, result which is summation of these will be 4..
at last , function delete dynamically allocated memory of allocated array
as it is bit difficult to explain in details in one go, feel free to ask if you cannot get any point in explanation..
0
Whoa, this is a very bad practice, giving the same name to functions that operate differently.
0
Bebida Roja it's not a practice, it's concept called overloading of function... Function to be called depends on type of arguments passed to function or number of arguments passed to the function
0
Ketan Lalcheta Yes, but overloaded functions should behave more or less the same because if not, one of them is badly described.