Arista Network Interview Experience
Anonymous User
1102

The interview started with a debugging problem from GFG
What will the output and why?

#include <iostream>
using namespace std;

void function(int *p) {
    int x = 100;
    p = &x; 
}

int main() {
    int a = 10;
    int *ptr = &a;
    function(ptr);
    cout << "Value: " << *ptr << endl; 
    return 0;
}

Q: what will be printed?
A: Value: 10

This happend because funtion creates the own copy of variable *p. So, the value will not presist going out of scope of function.

After this I was asked what could be changed in "function" to make it work intended i.e, print 100.

corrected solution

#include <iostream>
using namespace std;

void function(int *p) {
    int x = 100;
    *p = x; // we placed the value of x at memory location of p
}

int main() {
    int a = 10;
    int *ptr = &a;
    function(ptr);
    cout << "Value: " << *ptr << endl; 
    return 0;
}
Comments (1)