How does this code function and what is "new int[2]"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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); }

30th Jul 2018, 4:00 PM
Yelyzaveta Al-Dara
5 Answers
+ 1
Bebida Roja do agree...at least delete nd allocate function should have different name
31st Jul 2018, 9:59 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
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..
30th Jul 2018, 4:12 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Whoa, this is a very bad practice, giving the same name to functions that operate differently.
30th Jul 2018, 6:44 PM
Bebida Roja
Bebida Roja - avatar
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
31st Jul 2018, 1:38 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta Yes, but overloaded functions should behave more or less the same because if not, one of them is badly described.
31st Jul 2018, 9:53 AM
Bebida Roja
Bebida Roja - avatar