Issue
#include <stdio.h>
int *sum_returning_pointer(int *x, int *y)
{
// Call be reference
int z = (*x) + (*y);
return &z;
}
void main(int *argc, char *argv[])
{
int a = 1, b = 2;
int *p = sum_returning_pointer(&a, &b);
printf("Sum = %d\n", *p);
}
With the above function i'm trying to add up the two numbers which are passed as a reference to the called function and returning pointer pointing to the variable where sum is stored. But i'm getting weird error saying.
Error has occured.
Segmentation Fault.
What does this error mean? How can i achieve a solution ? Why does this error occurs ?
Solution
In main function z is not accessible that's why it is showing undefined behavior. You can declare z as a global variable like
#include <stdio.h>
int z =0;
int * sum_returning_pointer(int *x, int *y)
{
// Call be reference
z = (*x) + (*y);
return &z;
}
void main(int *argc, char *argv[])
{
int a = 1, b = 2;
int *p = sum_returning_pointer(&a, &b);
printf("Sum = %d\n", *p);
}
Answered By - rajnish kumar Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.