指向字符串的指针 [英] pointer to strings
问题描述
下面的两个代码段可编译,没有任何错误/警告,但运行时会崩溃.请赐教.
The following two code snippets compiles without any errors/warnings but while running it crashes. Kindly enlighten me.
程序1
int main( )
{
char *p= "Hello" ;
*p = 'B' ;
printf("\n%s",p);
return 0;
}
程序2
int main( )
{
char *p= "Hello" ;
Char *q="mug"
*q = *p ;
printf("\n%s",q);
return 0;
}
对于程序2,我希望输出为拥抱".
For program 2 i expected output to be 'Hug'.
推荐答案
当您这样做:
char *p= "Hello";
您正在定义字符串文字.字符串文字是常量数据,正如您所发现的那样,对其进行修改会导致未定义的行为(通常是崩溃).应该声明为:
You are defining a string literal. String literals are constant data and as you've found out, modifying them results in undefined behavior (often a crash). It should be declared as:
const char *p = "Hello";
因此,如果您尝试修改它,编译器将抛出错误.
So the compiler will throw an error if you try to modify it.
现在,如果您将其定义为:
Now if you define it instead as:
char p[] = "Hello";
然后将内存分配到堆栈上,您可以对其进行修改.
The memory is then allocated on the stack and you can modify it.
int main(int argc, char *argv[])
{
char p[] = "Hello" ;
*p = 'B' ;
printf("\n%s",p);
return 0;
}
输出Bello
对于程序2,请注意只需将q
放在堆栈中. p
可以仍然是指向字符串文字的const
指针,因为您只是从中读取.
For program 2, note only q
needs to be on the stack. p
can remain a const
pointer to a string literal, since you're only reading from it.
int main( )
{
const char *p = "Hello" ;
char q[] = "mug";
*q = *p ;
printf("\n%s",q);
return 0;
}
输出Hug
这篇关于指向字符串的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!