为什么不是'src`改变,当我从函数改变呢? [英] Why isn't `src` changing when I change it from the function?

查看:122
本文介绍了为什么不是'src`改变,当我从函数改变呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序:

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;字符* STR(字符* SRC); \\\\宣布为全球功能
主要()
{
    焦炭SRC [40] =你好;
    clrscr();
    看跌期权(SRC);
    STR(SRC); \\\\函数调用
    看跌期权(SRC); \\\\不把更改的字符串?
    残培();
    返回0;
}字符* STR(字符* SRC)
{
    SRC =读者; \\\\改变我的源字符串< - 是它改变?
    返回SRC; \\\\返回源刺痛
}

输出:


 你好
你好


为什么的src 不成为读者


解决方案

在您的code, SRC =读者; 是错误的。你必须尝试像

 的strcpy(SRC,读者);

究其原因, C 按值传递使用,而通过函数的参数。因此,的src 这里是按值传递的,所以你不能的src 在函数内部改变。您可以 * SRC 从功能上发生改变。因此,要改变由的src 所指向的内容,你必须使用的strcpy()

此外,作为先生的 @coolguy 提到,你不使用的返回值STR(),所以收益语句在这里做没有任何影响。

My program:

#include<stdio.h>
#include<conio.h>

char* str(char*src);\\declared as function global
main()
{
    char src[40]="hello";
    clrscr();
    puts(src);
    str(src);\\ function called
    puts(src);\\does not put changed string?
    getch();
    return 0;
}

char* str( char *src)
{
    src="readers";\\changing my source string<--is it changes???
    return src;\\returning source sting
}

output:

hello
hello

Why is src not becoming "readers"?

解决方案

In your code, src="readers"; is wrong. You have to try like

strcpy(src, "readers");

The reason is, C uses pass by value while passing function parameters. So, src here is passed by value, so you cannot change src from inside the function. You can change *src from the function. So, to change the content pointed by src, you have to use strcpy().

Also, as Mr, @coolguy has mentioned, you're not using the return value of str(), so the return statement is making no impact here.

这篇关于为什么不是'src`改变,当我从函数改变呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆