gpt4 book ai didi

c - 我的程序在调用 `strcpy()' 时崩溃

转载 作者:行者123 更新时间:2023-11-30 21:15:21 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char *str1 = "Bangladesh Bogus Party";
char *str2 = "Sad is a beautiful Country";

strcpy(str1 + 11, str2 + 4);
strcat(str1, "! !! !!!");
printf("\n%s", str1);

return 0;
}

在代码块中,它发现......

-------------- Build: Debug in catcpy (compiler: GNU GCC Compiler)---------------

Target is up to date.
Nothing to be done (all items are up-to-date).


-------------- Run: Debug in catcpy (compiler: GNU GCC Compiler)---------------

Checking for existence: E:\Sobar Jonno C (Niton)\String\catcpy\bin\Debug\catcpy.exe
Executing: "C:\Program Files (x86)\CodeBlocks/cb_console_runner.exe" "E:\Sobar Jonno C (Niton)\String\catcpy\bin\Debug\catcpy.exe" (in E:\Sobar Jonno C (Niton)\String\catcpy\.)

最佳答案

您无法覆盖指向 string literal because they are read only memorystr1 指针。并且您的程序正在尝试写入指针所指向的内存,这会导致未定义行为,大多数情况下会导致段错误。最糟糕的是,如果没有事先分配必要的空间,您就无法连接。

如果你想让你的代码正常工作,你需要这样的东西

#include <stdio.h>
#include <string.h>

int main(void)
{
char str1[42] = "Bangladesh Bogus Party";
const char *str2 = "Sad is a beautiful country";

strcpy(str1 + 11, str2 + 4);
strcat(str1, "! !! !!!");

printf("%s\n", str1);

return 0;
}

请注意,str1 不再是字符串文字,而 str2 则是。这是因为 str2 从未被修改,并且我添加了 const 说明符以防止意外执行此操作。完全阻止这种情况是不可能的,但是 const 可以帮助您注意到您无意中这样做的情况。

关于c - 我的程序在调用 `strcpy()' 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com