0

How can I write a function that receives two pointers of type INT as arguments? The function reads two integers from the user and stores them in its arguments. It then calculates the sum of the integers and returns the result.

Below is the code that I wrote. It was really crappy and contains a lot of error.

'''

 #include<stdio.h>

//function prototype
int sum(int* first, int* second);


//function definition
int sum(int* first, int* second)
{
int sum2;

*first = &p;
*second = &q;
sum2 = first + second;
printf("sum of the 2 numbers is %d", sum2);
return;
} 

void main()
{
int p;
int q;
printf("enter the two numbers two add");
scanf("%d %d", &p, &q);
sum(&p, &q);
 }

'''

  • Read [*Modern C*](https://modernc.gforge.inria.fr/), the documentation of your C compiler (e.g. [GCC](http://gcc.gnu.org/) ; invoke it as `gcc -Wall -Wextra -g` ...) and of your debugger (e.g. [GDB](https://www.gnu.org/software/gdb/)..) – Basile Starynkevitch Jan 13 '21 at 14:47
  • 2
    `*first = &p;` why this ? `first` already contains the address of `p`. Note also that `sum()`doesn't return anything – Damien Jan 13 '21 at 14:47

1 Answers1

1

Your function already accepts the addresses of your variables p and q in pointers first and second, so you access the variables using these pointers only:

int sum(int *first, int *second) {
    int sum2;
    // de-reference the first and second pointers to get the values
    sum2 = *first + *second;
    printf("sum of the 2 numbers is %d.\n", sum2);
    // you declared your function as 'int sum(int *, int *)', so return an int, it's not declared as 'void f(int *, int *)'
    return sum2;
}

Also, delcare main as int main():

int main() {
    // your code
    int sum_result = sum(&p, &q);
    return 0;
}
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • Thanks! this answer really helps. but can you explain why I cannot use void in my main function? I read this thread, https://stackoverflow.com/questions/3156423/why-dont-we-use-void-in-main but don't really understand the reason. – admincambest91 Jan 14 '21 at 13:50
  • You need your main method to return an integer code like 0 or 1 or -1 to indicate the result of execution, 0 for success, non-zero such as -1 for program exited unsuccessfully or exception, etc. With `void`, you don’t return anything so you don’t know how did the program execute, also C standard suggests to use `int main` as well. – Jarvis Jan 15 '21 at 00:12