<\/span><\/h2>\n\n\n\nIn this challenge, you will learn to implement the basic functionalities of pointers in C++. A pointer in C++ is a way to share a memory address among different contexts (primarily functions). They are primarily used whenever a function needs to modify the content of a variable that it does not own.<\/p>\n\n\n\n
In order to access the memory address of a variable, val, prepend it with & sign. For example, &val returns the memory address of val.<\/p>\n\n\n\n
This memory address is assigned to a pointer and can be shared among various functions. For example, int *p = &val will assign the memory address of val to pointer p. To access the content of the memory to which the pointer points, prepend it with a *. For example, *p will return the value reflected by val and any modification to it will be reflected at the source (val).<\/p>\n\n\n\n
void increment(int *v) {\n (*v)++; \n }\n \tint main() {\n int a;\n scanf(\"%d\", &a);\n increment(&a);\n printf(\"%d\", a);\n \treturn 0; \n } \n<\/pre>\n\n\n\n<\/span>Task<\/strong><\/span><\/h2>\n\n\n\nComplete the function void update(int *a,int *b). It receives two integer pointers, int* a and int* b. Set the value of a to their sum, b and to their absolute difference. There is no return value, and no return statement is needed.<\/p>\n\n\n\n
- a\u2019 = a+b<\/strong><\/li>
- b\u2019 = |a-b|<\/strong><\/li><\/ul>\n\n\n\n
<\/span>Input Format<\/strong><\/span><\/h2>\n\n\n\nThe input will contain two integers, a and b, separated by a newline.<\/p>\n\n\n\n
<\/span>Output Format<\/strong><\/span><\/h2>\n\n\n\nModify the two values in place and the code stub main() will print their values.<\/p>\n\n\n\n
Note:<\/strong> Input\/output will be automatically handled. You only have to complete the function described in the ‘task’ section.<\/p>\n\n\n\nSample Input<\/strong><\/p>\n\n\n\n4\n5\n<\/code><\/pre>\n\n\n\nSample Output<\/strong><\/p>\n\n\n\n9\n1\n<\/code><\/pre>\n\n\n\n<\/span>Explanation<\/strong><\/span><\/h2>\n\n\n\n- a\u2019 = 4 + 5 = 9<\/li>
- b\u2019 = | 4 – 5 | = 1<\/li><\/ul>\n\n\n\n
<\/span>Solution – Pointers in C++ HackerRank Solution<\/strong><\/span><\/h2>\n\n\n\n#include <stdio.h>\n\nvoid update(int *a,int *b) {\n \/\/ Complete this function \n int sum = *a+*b;\n int mult;\n if(*a>*b)\n {\n mult = *a-*b;\n } \n else\n {\n mult = *b-*a;\n }\n *a = sum;\n *b = mult;\n}\n\nint main() {\n int a, b;\n int *pa = &a, *pb = &b;\n \n scanf(\"%d %d\", &a, &b);\n update(pa, pb);\n printf(\"%d\\n%d\", a, b);\n\n return 0;\n}\n<\/pre>\n\n\n\n