Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
this is to to take out sum of three no using calling function but here i have used pointer so what hell the difference has been created and why segmentation fault is the output

What I have tried:

int *calsum(int x,int y,int z);
int main()
 int a,b,c,sum;
 printf("Enter any3 numbers");
 int *calsum (int x,int y,int z)
 return x+y+z;
Updated 21-Feb-17 9:05am
[no name] 21-Feb-17 13:44pm    
Mostly because it's not C# code?

That's not C# - that's "straight" C, or very-much-beginner-C++.
And if you look closely at what your calcsum returns, the problem is pretty obvious.
What is x + y + z where x, y, and z are all integers?
Simple: it's an integer, just as 666, 42, and 7 are all integers. What that isn;t is a pointer-to-an-integer which is what the function says it is returning, and your code assumes it actually is and dereferences the pointer. Since "666" isn't a pointer into valid memory, the system rightly assumes your program is broken, and issues a segmentation fault.
Take out the "*" from the function definition, and from the line where you call it. It'll work then.
Share this answer
First, this return an integer, not a pointer to an integer
return x+y+z;

Second, the value is on stack, so even if the pointer id as expected, the value will be trashed the call to printf.
You a lot of lecture ahaed to learn seriously C and C++.

Here is links to references books on C and C++ by the authors of the languages. Note than C is the ancestor of C++, so knowing C is always useful with C++.
The C Programming Language - Wikipedia, the free encyclopedia[^][^][^]

C++ Programing Language[^]

Learning to use the debugger will help too.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900