0

I solved this simple question in C on my lab's system (which uses Windows). I used DevC++ to write this code and it ran on DevC++, but I cannot compile the same code on my Mac system.

Code:

#include<stdio.h>
#include<stdlib.h>

int* oddSwap(int x, int y)
{
    int temp = x;
    x = y * 5;
    y = temp * 5;
    int *k;
    *k=x+y;
    return k;
}

int main()
{
    int x=5;
    int y=3;
    int *k=oddSwap(x,y);
    printf("\n%d", *k);
    return 0;
}

This ran on Windows (DevC++), but I'm getting this error message on running it on macOS (macOS 10.14.2).

Bus error: 10
bruno
  • 32,421
  • 7
  • 25
  • 37

2 Answers2

0

There is an error in your code.

int* oddSwap(int x, int y)
{
    int temp = x;
    x = y * 5;
    y = temp * 5;
    int *k; // <-- the pointer 'k' is never given a value, yet you de-reference it below.
    *k=x+y; // <-- this operation is invalid.
    return k;
}

When you do *k = <something> you dereference the pointer.

That is, you assign <something> to the variable that k points to.

For that to be valid, you need to give k a value, i.e. make it point to something.

Morten Jensen
  • 5,818
  • 3
  • 43
  • 55
0

The swap-function does not make much sense, since you swap the arguments only within the function, but the result then combines both values with commutative operator + (so why swap at all?).

And you assign a value to a pointer that does not point to a valid object: int *k; *k=x+y;. But anyway, the complete operation does not make sense to me.

Maybe you wanted something like that:

void oddSwap(int *x, int *y)  {
   int temp = *x;
   *x = *y * 5;
   *y = temp * 5;
}

int main()
{
    int x=5;
    int y=3;
    oddSwap(&x,&y);
    printf("\n%d:%d", x,y);
    return 0;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58