【问题标题】:Why doesn't my compiler want to compile this code?为什么我的编译器不想编译这段代码?
【发布时间】:2019-06-02 16:46:14
【问题描述】:

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

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

【问题讨论】:

  • (a) 当您的编译器不想编译某些代码时,它会在错误消息中告诉您原因。如果您在理解某条消息时遇到困难,您应该在问题中包含它的确切文本。 (b) &lt; stdio .h &gt;&lt; stdlib .h &gt; 是错误的,因为有空格。删除空格。 (c) 指针是地址,或者至少指针对象的值是内存中的地址。返回指针的函数返回地址(或NULL)。 (d) 返回result的地址是不合适的,因为result的存在(在C执行模型中)只为sub的执行而存在。
  • 在您return &amp;result; 的第一段代码中,您将返回一个指向位于堆栈中的局部变量的指针。这是一个非常糟糕的主意。

标签: c function pointers compilation


【解决方案1】:

只需删除 import 语句中和周围的空格:

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

【讨论】:

    【解决方案2】:

    您是从哪里看到这段代码的?不需要 sub 方法,也不需要那些指针,实际上所有这些代码都是多余的。这是“固定”的:

    #include <stdio.h>
    
    int
    main()
    {
        printf("4\n");
        return 0;
    }
    

    但这听起来有点像学校作业。

    【讨论】:

    • 可能是学校作业,有人将其上传到 c 编程驱动器中。显然我也想到了这个答案,但是上传它的人问是否有任何方法可以正确放置指针和地址。所以我回复她说可以全部删除。我的问题是我在第一个代码中的解释是否正确。
    • 好的,在这种情况下,除了#includes 中的奇怪间距和没有缩进之外,代码是正确的。
    【解决方案3】:

    取消引用指针并对内存分配进行一些技巧:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-27
      • 2012-02-14
      • 2012-07-06
      • 2013-08-08
      • 1970-01-01
      • 2014-09-14
      • 2010-10-24
      相关资源
      最近更新 更多