Li Li
Li Li

Reputation: 23

Integer pointers to a function

I have a dumb question. I'm trying to write a program that will get two numbers from a function and send them back to the main, where I can use them. However, when I run the code below, the only values returned are always zero. Should I change my pointers?

#include <stdio.h>

void get(int *num1, int *num2);

int main(void)
{
    int num1, num2, input;
    get(&num1, &num2);

    printf("Num1 is %d and num2 is %d.\n", num1, num2);
    return 0;
}

void get(int *num1, int *num2)
{
    printf("Enter two numbers. \n");
    printf("Number 1: \n");
    scanf("%d", &num1);

    printf("Number 2: \n");
    scanf("%d", &num2);
    printf("In function, %d and %d.\n", num1, num2);

    return;
}

Upvotes: 0

Views: 91

Answers (3)

Beta
Beta

Reputation: 99094

You are assigning values to the pointers, not to the things they point to. Try either this:

scanf("%d", num1);

or (in C++) this:

void get(int &num1, int & num2)
{
  ...
  printf("Number 1: \n");
  scanf("%d", &num1);
  ...
  return;
}

int main(void)
{
  ...    
  get(num1, num2);
  ...
  return 0;
}

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881243

First, there are no dumb questions. Well, there are, but this isn't one of them :-)

In get, the num1 and num2 variables are already pointers to the integers, you shouldn't prefix them with &.

However, you should dereference the pointers in the printf within the function. See the following code for how to do it (along with some cosmetic changes not really relevant to the question at hand).

#include <stdio.h>

void get(int *num1, int *num2) {
    printf("Enter two numbers.\n");

    printf("Number 1: ");
    scanf("%d", num1);                                   // << No &

    printf("Number 2: ");
    scanf("%d", num2);                                   // << No &

    printf("In function, %d and %d.\n", *num1, *num2);   // Add *'s
}

int main(void) {
    int num1, num2, input;
    get(&num1, &num2);
    printf("Num1 is %d and num2 is %d.\n", num1, num2);
    return 0;
}

Sample run:

Enter two numbers.
Number 1: 5
Number 2: 8
In function, 5 and 8.
Num1 is 5 and num2 is 8.

Upvotes: 2

Vijay
Vijay

Reputation: 67211

num1 and num2 inside the function are already pointers.

so inside scanf change &num1 to num1 and &num2 to num2.

#include <stdio.h>


void get(int *num1, int *num2);

int main(void)
{
    int num1, num2, input;
    get(&num1, &num2);

    printf("Num1 is %d and num2 is %d.\n", num1, num2);
    return 0;
}

void get(int *num1, int *num2)
{
    printf("Enter two numbers. \n");
    printf("Number 1: \n");
    scanf("%d", num1);

    printf("Number 2: \n");
    scanf("%d", num2);
    printf("In function, %d and %d.\n", num1, num2);

    return;
}

Upvotes: 1

Related Questions