为什么我在运行时遇到此错误?

时间:2013-08-10 01:12:27

标签: c

我在观看教程时编写了这个程序来比较C中“按值调用”和“按引用调用”之间的区别。但是我收到了错误:

  

运行命令:第1行:1508分段错误:11 ./“$ 2”“$ {@:3}”

帮助?

main() 
{
int a,b;
scanf("%d %d", &a, &b);
printf("Before Call %d %d", a,b);
exch_1(a,b);
printf("After first call %d %d", a,b);
exch_2(a,b);
printf("After second Call %d %d \n", a,b);  

}

exch_1(i,j)
int i, j;
{
    int temp;
    temp = i;
    i = j;
    j = temp;
}

exch_2(i,j)
int *i, *j;
{
    int temp;
    temp = *i;
    *i = *j;
    *j = temp;
}

2 个答案:

答案 0 :(得分:5)

由于exch_2期望地址作为参数,您必须将其称为exch_2(&a,&b);

您正在传递值,这些值被视为地址。如果是。 G。 a的值为5,计算机会尝试使用您计算机上地址5的值 - 这可能是您的程序无法访问的。

答案 1 :(得分:0)

以下是您问题的正确代码。使用gcc -Wall编译原始代码。它会为您的上述代码提供大量警告,并且您最好需要修复所有这些代码。 如果你不了解linux和gcc,请学习它。不要使用turboC编译器等旧工具

void exch_1(int i, int j);   // declare function prototype for exch_1 --> call by value
void exch_2(int* i, int* j);  // declare function prototype for exch_1 --> call by reference

int main()
{
    int a,b;

    scanf("%d %d", &a, &b);
    printf("Before Call %d %d\n", a,b);

    exch_1(a,b);  // call by value. changes done in exch_1 are not reflected here
    printf("After first call %d %d\n", a,b);

    exch_2(&a, &b);   // --> please see the change here for call by reference, you 
                      //should  pass address as the parameters
                      // changes done in exch_2 can be seen here since we pass address
                      // In you original program you are passing value of a and b as the 
                      // address.When you try to access those values in exch_2 the it leads
                      // to undefined behavior and so you can get segfault as well.
    printf("After second Call %d %d \n", a,b);

    return 0;    
}

void exch_1(int i,int j)
//int i, j;    // you do not need these variables
{
    int temp;
    temp = i;
    i = j;
    j = temp;
}

void exch_2(int* i,int* j)
//int *i, *j;   // this line not needed
{
    int temp;
    temp = *i;
    *i = *j;
    *j = temp;
}