传递字符串作为参数通过的char * [英] Pass string literal as char* via argument
问题描述
我做了哪些修改字符串的函数,请参阅以下code。
I made a function which change string, see the following code.
void Test(char* str, char c) {
str[1] = c;
}
int main(){
Test("Hi", '2');
}
我注意到它做了一些运行时错误。我知道如何prevent错误。
I notice it made some run time error. I know how to prevent the error.
char buff[3] = "Hi";
Test(buff,'2');
但我不知道为什么第一个例子做运行时错误。我想,如果我直接传递字符串,就变成为const char。没有人解释究竟发生什么事呢?
but I don't know why the first example made run time error. I guess, if I pass string directly, it becomes const char. Does anyone explain what happened exactly?
PS。
如果我用的char *海峡=然后将它传递到参数?
ps. what if I use char* str = "hi", then pass it into the argument?
char* buff = "Hi";
Test(buff,'2');
这样。我可以修改BUFF?
like this. Can I modify buff?
推荐答案
由于嗨
是文字的,这是不允许的字符串是修改,它们是只读的(字符串类型为为const char [N]
)。
Because "Hi"
is string literal and it's not allowed to be modified, they are read-only (the type of string literal is const char[n]
).
修改它的未定义行为的
关于您的编辑:的char *海峡=喜
是无效的,应该是为const char *海峡=喜
。这是指向为const char
。再次,修改它被禁止。
Regarding your edit: char* str = "hi"
is invalid, it should be const char* str = "hi"
. Which is pointer to const char
. Again, modifying it is disallowed.
这篇关于传递字符串作为参数通过的char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!