为什么在函数中设置的变量会丢失?

时间:2014-08-14 13:06:32

标签: c function

我试图通过函数传递c中的参数。带有字符串参数的版本工作正常,但带有整数参数的两个版本都返回1作为结果。

#include<stdio.h>

void main() 
{
    char s1[10];
    int a,b;
    clrscr();

    printf("name=%s\n",getname(s1));
    printf("mobile=%d\n",getmobile(a));
    printf("mobile=%d\n",getrno(b));

    getch();
}

getname(char s[10])
{
    printf("enter the name\n");
    gets(s);
    return ;
}

getmobile(int a)
{
    printf("enter the mobile number\n");
    scanf("%d",&a);
}

getrno(int b)
{
    printf("enter the rno\n");
    scanf("%d",&b);
} 

2 个答案:

答案 0 :(得分:3)

getname工作的原因是getrno不是因为传递引用与值传递语义,而是因为数组,如s1 { {3}}。如果您想用C编程,这些是要理解的重要概念。

可以这样想:当你致电getname时,它会接受缓冲区地址的本地副本。然后该函数写入缓冲区本身。但是当你调用getrno时,函数会接受一个整数的本地副本,并将值读入该本地副本,以便程序外部没有任何变化。

@askmish提出了一个很好的解决方案,但我强烈建议这样的事情:

// getrno will prompt the user to enter the rno and will store it into the variable
// pointed to by b. If the function returns 1 then a value was successfully read. 
int getrno(int* b)
{
    // make sure that the pointer looks valid
    if (b == NULL)
        return 1;

    // prompt the user to enter the text
    puts ("enter the rno: ");

    // Note the use of a single space at the beginning of the format string
    // which is used to consume any whitespace (including return characters
    // that might be present)
    if (scanf (" %d", b) == 1)
        return 0;

    // We couldn't read one integer. Return an error.
    return 1;
}

int main() 
{
    int x;

    if (!getrno (&x))
        printf ("rno = %d\n", x);
    else
        printf ("failed to get rno!");

    return 0;
}

你问如何做浮点数。解决方案是编写一个函数,根据需要接受floatdouble指针,然后使用正确的格式说明符调用scanf,以将值读入该指针。这个函数看起来非常像我上面给你的getrno

答案 1 :(得分:-1)

函数应该像这样写,例如:

        int getrno(int b)
        {
                printf("enter the rno\n");
                scanf("%d",&b);
                return b;
        } 

获取返回值aka,它必须具有return-type和return语句,返回指定返回类型的值。你的代码都丢失了。

我还建议你阅读一本好的书,或者在wikibooks中阅读至少this page,以便更好地理解和编写更好的代码。