mesun_99
mesun_99

Reputation: 37

Why doesn't my compiler want to compile this code?

Yesterday I came across this problematic code that I have been meaning to understand and correct. So far I have done some research and corrected it, but I was wondering whether there are other ways to correct the code?

# include < stdio .h >
# include < stdlib .h >
int * sub ( int * x , int * y) { //return type should be pointer but is address//
int result = y - x ; //integer becomes pointer//
return &result;
}
int main ( void ) {
int x = 1;
int y = 5;
int * result = sub (&x , &y ); //function has addresses as parameters but not pointers//
printf ("% d\n" , * result );
return EXIT_SUCCESS ;
}

I would have simply deleted all pointers and addresses:

# include < stdio .h >
# include < stdlib .h >
int sub ( int x , int y) {
int result = y - x ;
return result ;
}
int main ( void ) {
int x = 1;
int y = 5;
int result = sub (x , y );
printf ("% d\n" , result );
return EXIT_SUCCESS ;
}

Upvotes: 0

Views: 120

Answers (3)

S.S. Anne
S.S. Anne

Reputation: 15576

Dereference the pointers and do some trickery with memory allocation:

#include <stdio.h>
#include <stdlib.h>
int *sub (int *x, int *y) {
    int *result = malloc(sizeof(*result));
    *result = *y - *x;
    return result;
}
int main (void) {
    int x = 1;
    int y = 5;
    int *result = sub(&x, &y);
    printf("%d\n", *result );
    return EXIT_SUCCESS;
}

Upvotes: 0

jazz64
jazz64

Reputation: 339

Just remove the spaces in and around the import statements:

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

int sub(int x, int y)
{
  int result = y - x;
  return result;
}

int main(void)
{
  int x = 1;
  int y = 5;
  int result = sub(x, y);
  printf("% d\n", result);
  return EXIT_SUCCESS;
}

Upvotes: 2

Sabrina Jewson
Sabrina Jewson

Reputation: 1518

Where did you come across this code? There is no need for the sub method, and no purpose for those pointers, in fact all of this code is redundant. Here is it 'fixed':

#include <stdio.h>

int
main()
{
    printf("4\n");
    return 0;
}

But this sounds suspiciously like a school assignment.

Upvotes: 0

Related Questions