Here i am executing a simple code in C. It is compiling fine but traps during run time.
#include <stdio.h>
#include <conio.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
void main()
{
int a=10,b=20,*c;
sum(a,b,c);
printf("sum is %d\n",*c);
}
Can someone point out what is the issue? Also, how does one pass a pointer to a function?
Your mistake is that you have passed an uninitialized integer pointer to a function and then used the pointer. What you probably intended to do was to automatically allocate an integer on the stack and then pass the address of said integer to the function.
#include <stdio.h>
#include <conio.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
void main()
{
int a=10,b=20,c; // Automatically allocate an integer on the stack
sum(a,b,&c); // Third argument is the address of the integer
printf("sum is %d\n",c);
}
The key thing is to remember that when you do int *c you are allocating a pointer, when you do int c you are allocating an integer. If you wish to modify a variable passed to a function, the typical pattern in C is to pass the address of said variable but you first need to allocate the proper type, in this case an int and not an int *. You can then use the address of operator & to obtain the address of the relevant data which you then pass as the function argument.
Problem in your above program is unitialized pointer c. So you can allocate memory to c using malloc -
#include <stdio.h>
#include <stdlib.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
int main() // declare main as int.
{
int a=10,b=20,*c;
c=malloc(sizeof(int)); //allocating memory to pointer c
sum(a,b,c);
printf("sum is %d\n",*c);
free(c); // freeing allocated memory
retrirn 0;
}