为什么我的编译器不想编译此代码?

时间:2019-06-02 16:46:14

标签: c function pointers compilation

昨天,我遇到了这个有问题的代码,我一直想去理解和纠正它。到目前为止,我已经进行了一些研究并进行了纠正,但我想知道是否还有其他方法可以纠正代码?

# 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 ;
}

我只是删除了所有指针和地址:

# 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 ;
}

3 个答案:

答案 0 :(得分:1)

只需删除导入语句中及其周围的空格:

#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;
}

答案 1 :(得分:0)

您在哪里遇到此代码?不需要子方法,也不需要这些指针,实际上所有这些代码都是多余的。这是“固定的”:

#include <stdio.h>

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

但这听起来像是学校的任务。

答案 2 :(得分:0)

取消对指针的引用,并对内存分配进行一些欺骗:

map