1

as I am starting to study at university we are learning how to write in C and we got to the point where I've learned that I can use pointers as function parameters but what they haven't told us is how to get the value from it. I am not able as a person who doesn't know about C as much, to come up with other solution than use two parameters (one as pointer to the variable and other as value. See the example which is not real code but it's just for purpose of demonstration:


int main(int argc, char* argv []) {

     int a;
     addNumber(&a);


}

void addNumber(int * a) {
     *a = *a + 1; // this obviously does not work
}


Any input would be appreciated. Thanks!

3 Answers 3

3

Only one major thing: You forgot to initialize a. Otherwise, it looks fine.

 int a = 0;
 addNumber(&a);

The only other thing is that you're missing the return statement in main.

Sign up to request clarification or add additional context in comments.

3 Comments

a is not initialized, maybe that's why the OP thinks it doesn't work?
and a is missing an initialization value.
And C99, regrettably, sanctions omitting that return - to follow C++98 which also sanctions the omission of the return from main(). The effect is as if you wrote return 0;.
0

Here is an example that may be closer to what you are looking for:

#include <stdio.h>

void increment(int *a, int *b)
{
    *a = *a + *b;
}

int main(void)
{
    int sum = 5;
    int increment_by = 7;
    printf("sum: %d, increment_by: %d\n", sum, increment_by);
    increment(&sum, &increment_by);
    printf("sum: %d, increment_by: %d\n", sum, increment_by);

    return 0;
}

output:

$ ./bar
sum: 5, increment_by: 7
sum: 12, increment_by: 7

3 Comments

Thanks I didn't realize it would make such a difference.
So others can learn - what part of my answer made a difference for you?
The inicialization, From you example and by comparing it to my code I immediately realized that I forgot to inicialize the variables and I didn't realize it would cause the problem. Rookie mistake. :-)
0

It will work. It will work better if you initialise a, to some value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.