简体   繁体   English

strcpy函数,带有指向字符数组的指针

[英]strcpy function with pointers to character array

In the code below the result is stack overflow. 在下面的代码中,结果是堆栈溢出。 Though null character is there with both the strings, so the strcpy loop should terminate as the source string has null character. 尽管两个字符串都存在空字符,但由于源字符串具有空字符,因此strcpy循环应终止。 Why stack overflow occurs?? 为什么会发生堆栈溢出?

#include <stdio.h>
#include<strings.h>
int main(void) {
    char *str="Hello world";
    char *str1="Good morning";
    strcpy(str,str1);
    printf("%s",str);
    return 0;
}

The error isn't stack overflow, but modifying a string literal. 该错误不是堆栈溢出,而是修改了字符串文字。

str is a pointer that points to a string literal "Hello world" , and modifying a string literal is undefined behavior. str是一个指向字符串文字"Hello world"的指针,修改字符串文字是未定义的行为。

Change str to: str更改为:

char str[100] = "Hello world";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM