英文:
Function changes the value of the given argument
问题
我正在将我在主函数中声明的 Test
变量传递给 tf 函数。如果我在 tf
中对 argument
进行更改,实际的 Test
变量也会更改。
是否有任何方法可以在不创建另一个变量的情况下阻止这种情况发生?
代码
#include <stdio.h>
void tf(char *argument){
argument[0] = 'Z';
}
int main() {
char Test[5] = "Hello";
printf("'Test' 在调用 tf 函数之前 : %s\n",Test);
tf(Test);
printf("'Test' 在调用 tf 函数之后 : %s\n",Test);
return 0;
}
输出
'Test' 在调用 tf 函数之前 : Hello
'Test' 在调用 tf 函数之后 : Zello
我在网上搜索了这个问题,但没有找到有用的信息。
英文:
I'm passing the Test
variable that I declared in my main function to tf function. If I make a change to the argument
in tf
, the actual Test
variable changes.
Is there any way to prevent this without creating another variable in the tf
function?
The Code
#include <stdio.h>
void tf(char *argument){
argument[0] = 'Z';
}
int main() {
char Test[5] = "Hello";
printf("'Test' before calling tf function : %s\n",Test);
tf(Test);
printf("'Test' after calling tf function : %s\n",Test);
return 0;
}
The Output
'Test' before calling tf function : Hello
'Test' after calling tf function : Zello
I googled the problem but I didn't found anything useful.
答案1
得分: 2
在我的电脑上,你的代码显示出垃圾数据。
这是错误的,它保留了5个字符,而"Hello"的长度是5,所以没有空间用于终止的NUL字符:
char Test[5] = "Hello";
不要指定长度,让编译器完成它的工作:
char Test[] = "Hello";
话虽如此,第一个字符被修改成'z'是正常的,argument
指向你的原始字符串。你期望什么?
没有办法防止这种情况,除非在tf
函数中创建另一个变量,你需要复制字符串并在复制上操作。
但问题是:你实际上想要实现什么?
英文:
For starters:<br>
On my computer your code displays garbage.
This is wrong, it reserves 5 chars and the length of "Hello" is 5, so there is no room for the terminating NUL character:
char Test[5] = "Hello";
Don't specifiy the length but let the compiler do it's job:
char Test[] = "Hello";
That being said, it's normal that the first character is modified into 'z', argument
points to your original string. What do you expect?
There is no way to prevent this without creating another variable in the tf
function, you need to make a copy of the string and operate on the copy.
But the question here is: what are you actually trying to achieve?
答案2
得分: 1
你不改变参数本身,而是改变参数所指向的内存。为了避免这种情况,将参数声明为指向常量的指针:
void tf(const char *argument) {
argument[0] = 'Z'; // 编译时错误
}
英文:
You don't change the argument, you change the memory where the argument is pointed to. For avoiding it, make the parameter to point to const:
void tf(const char *argument) {
argument[0] = 'Z'; // Compile time error
}
答案3
得分: 0
如果您想要两份字符串的副本,您需要将其存储在某处。无论您是在函数内部还是外部进行复制都由您决定。
例如,
void tf( const char *argument ) {
char *copy = strdup( argument );
copy[0] = 'Z';
// 在此处对`copy`进行操作。
free( copy );
}
英文:
If you want two copies of the string, you will need to store it somewhere. Whether you make the copy inside or outside the function is up to you.
For example,
void tf( const char *argument ) {
char *copy = strdup( argument );
copy[0] = 'Z';
// Do something with `copy` here.
free( copy );
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论