marko marko -4 years ago 100
C++ Question

Why pointer return 0 in foor loop

I have the following function:

void printKMax(int arr[], int n, int k){
int* start = &arr[0];
int* run = new int();
if(n > 1){
int* run = &arr[1];
cout << "Initial run pointer " << *run << endl;
}else {
cout << *start << endl;
return;
}
for(int i = 0; i < k-1; i++){
cout << "Run in for loop " << *run << endl;
}
delete run;
}


Input
arr = {3 4 6 3 4}
and
k = 4
.
First cout prints
4
, while for loop cout prints
0
three times. Why does it give
0
and not
4
? Why is dereferencing the pointer in for loop different than in if statement?

Answer Source

In this declaration

int* run = new int();

there is declared pointer run that points to the dynamically allocated memory initialized by zero.

It is the variable that is used in the loop

for(int i = 0; i < k-1; i++){
    cout << "Run in for loop " << *run << endl;
}   

Another pointer with the same name declared in the if statement

if(n > 1){
    int* run = &arr[1];

is not alive outside the if statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download