peki
peki

Reputation: 681

How to appropriately use pointers in C++ functions?

I'm trying to get the hang of pointers and addresses in C++ and am having trouble with functions with changing parameters.

The code below is writing Loop run #1. in an infinite loop, instead of incrementing the value foo.

My question is: What is the issue with this code here?

#include <iostream>

void Statement(int *foo) {
    std::cout << "Loop run #" << *foo << ". ";
    foo++;
}

int main() {

    int foo = 1;

    for (;;) {
        Statement(&foo);
    }

}

Upvotes: 1

Views: 158

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

If I have understood correctly what you are trying to do then the function should be declared the following way as it is shown in the demonstrative program

#include <iostream>

void Statement(int *foo) {
    std::cout << "Loop run #" << *foo << ". ";
    ++*foo;
}

int main() {

    int foo = 1;

    for (; ; ) {
        Statement(&foo);
    }
}

That is in an infinite loop you are trying to output incremented value of foo.

In this case you have increment the value itself pointed to by the pointer like

++*foo

If you want to limit loop iterations then you can use for example an object of the type unsigned char and define the loop the following way

#include <iostream>

void Statement( unsigned char *foo) {
    std::cout << "Loop run #" << int( *foo ) << ". ";
    ++*foo;
}

int main() {

    unsigned char foo = 1;

    for (; foo ; ) {
        Statement(&foo);
    }
}

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36463

You're incrementing a copy of the pointer itself, not what it points to. You probably meant:

(*foo)++;

This still won't fix the infinite loop though because you have nothing to stop it with.

Upvotes: 8

Paul Belanger
Paul Belanger

Reputation: 2434

Your issue is that you're incrementing the pointer, not the pointed-to data.

replace

foo++

with

(*foo)++

to increment the pointed-to value.

Upvotes: 5

Related Questions