strcpy 在 wsl 中没有达到预期

问题描述 投票:0回答:1

我正在使用 wsl 和 gcc 编译器编写 c 代码。我尝试使用 strcpy 删除 c 字符串前面的空格,但得到了一个奇怪的结果。 我尝试修改的字符串是 s = {' ','e','h','c','o' ,' '};并且我使用指针 temp 指向字符串中的“e”,然后我使用 strcpy(s,temp) 删除空格。但是我得到的结果是 ecoo,而不是 echo。

#include  <stdio.h>
#include  <unistd.h>
#include  <string.h>
int main(){
    char a[256];
    a[0] = ' ';
    a[1] = 'e';
    a[2] = 'h';
    a[3] = 'c';
    a[4]  = 'o';
    a[5] = '\0';
    char* temp = a;
    temp ++ ;
    printf("%s\n",temp);
    strcpy(a,temp);
    printf("%s\n",a);
    
}

我尝试在程序中调试,temp确实是“echo”,但结果是ecoo。 代码在windows系统中Visual Studio和vscode中按照预期运行。 我还尝试了不同的字符串长度,发现当字符串长度为 3,7 时代码运行良好。 enter image description here

c linux windows-subsystem-for-linux strcpy
1个回答
1
投票

您的代码无效。来自 https://en.cppreference.com/w/c/string/byte/strcpy :

如果字符串重叠,则行为未定义。

temp
等于
a + 1
- 它们重叠。
strcpy(a, a + 1)
无效。

© www.soinside.com 2019 - 2024. All rights reserved.