[REPOST]为什么按值调用不适用于字符串操作功能 [英] [REPOST] why does call by value not work for string manipulation functions

查看:129
本文介绍了[REPOST]为什么按值调用不适用于字符串操作功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
void callbyvalue1(char a[],char b[])
{
char *x;
x=a;
a=b ;
b=x;
}
void callbyvalue2(char a[],char b[])
{
strcat(a,b);
}
void main()
{
char a[10],b[10];
scanf("%s%s",&a,&b);
callbyvalue1(a,b);
printf("%s\t%s",a,b);
callbyvalue2(a,b);
printf("%s\t%s",a,b);
}


输入:
a = hai
b =你好
callbyvalue1和callbyvalue2之后的输出是什么

[这是与最近发布的问题完全相同的重新发布.我不记得它是否是相同的查询者,但是代码示例是相同的.当时,询问者得到了全面的答复.该页面可能由于滥用情况报告而被删除;我不确定.

在所有情况下,这要么是重新发布,要么是与第一个问题来自同一来源的第二个问题;无论如何,都是某种虐待.

我重现了过去的答案,但不应该发生.

— SA]


Input:
a=hai
b=hello
what will be the output after callbyvalue1 and callbyvalue2

[This is the re-post of exact same question which was recently posted. I don''t remember if it was the same inquirer or not, but the code samples are identical. At that time, the inquirer got a comprehensive answer. The page could have been deleted due to abuse reports; I''m not sure.

In all cases, this is either a re-post or the second question copied from the same source as the first one; some kind of abuse, anyway.

I reproduced my past answer, but it should not happen.

— SA]

推荐答案

首先,在C语言中(而不是在C ++中)没有引用,并且参数传递机制始终是通过值.

在第一种情况下,您在堆栈上创建了一个指针x,并且从不使用它,因此该指针的值将被丢弃. ab不太明显.这些指针的值(不是指针引用的对象,而是指针)是堆栈上的副本并已修改.当您返回到调用方时,修改的值将被丢弃,因为已删除了堆栈框架.返回被调用后,这两个指针保持不变.

您是否只想交换两个对象?然后,您将需要使用指向指针的指针.

在第二种情况下,函数strcat返回一个值,但是您忽略该返回.请参阅: http://www.cplusplus.com/reference/cstring/strcat/ [ ^ ].

您可能会得到一条警告,建议您改用strcat_s,因为strcat被认为是不安全的.

—SA
First of all, in C (not in C++), there are no references, and the parameter-passing mechanism is always by value.

In first case, you create a pointer x on stack and never use it, so the value of this pointer is discarded. It''s less obvious with a and b. The values of these pointers (not objects referenced by them, but pointers) are copies on stack and modified. When you return to the caller, the modified values are discarded, because the stack frame is removed. After return to the called, these two pointers remain the same.

Did you want just to swap two objects? Then you would need to use pointers to pointers.

In second case, the function strcat returns a value, but you ignore the return. Please see: http://www.cplusplus.com/reference/cstring/strcat/[^].

You can get a warning recommending you to use strcat_s instead, as strcat is considered unsafe.

—SA


这篇关于[REPOST]为什么按值调用不适用于字符串操作功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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