problems with functions

Hi everybody. I wrote down two functions, but after compiling they return rubbish. As I understand they should return 5 and 7. Here is a code. Can somebody help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int compare(int i, int j)
{
    return i<j;
}

int* func(int *i, int j)
{
    i=&j;

    return 0;
}

int main()
{
    int a=4, b=7;
    int *c, f=5;

    cout<<*c<<endl;
    cout<<compare(a,b)<<endl;

    return 0;
}
return i<j;
this will return a bool and not the largest/smallest value
cout<<*c<<endl;
c is an uninitialized pointer, I assume you meant to call func before.

i=&j;
this will give pointer i the adress of j, but won't change the value of the parameter passed into the function, try:
*i=j;
After I changed to *i=j compiler wrote a segmentation fault.
And about first function I don't know how to do it right.
Last edited on
Don't worry about second function I figured it out by myself.
But what should I do with first one? Can somebody help?
Last edited on
Have you ever used if statements?
if(i<j) // If i is less/smaller than j
closed account (28poGNh0)
Maybe you look for this one

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <iostream>
using namespace std;

int compare(int i, int j)
{
    return (i<j)?j:i;
}

// No need for this function 

int main()
{
    int a=4, b=7;
    int *c, f=5;

    c = &f;// that's problem of your problem c point at location in memory

    cout << *c << endl;
    cout << compare(a,b) << endl;// I assume that you want the greatest value between 5 and 7

    return 0;
}

I tried to avoid using that short hand because it makes code more complex, especially for beginners, essentially what
return (i<j)?j:i;
does is evaluate a statement and return the first value if it's true and the second if it's false.
example:
1
2
3
4
if(i<j)
    return j;
else
    return i;


incase you were wondering
Topic archived. No new replies allowed.