字符串操作(剪切字符串的头部)

Jas*_*nLi 2 c

为什么我不能得到"xxx"?返回值是一些非常奇怪的符号...我希望返回的值是xxx,但我不知道这个程序有什么问题.该功能运行良好,可以为我打印"xxx",但一旦它返回值到main函数,字符串结果就不能很好地显示"xxx".有人可以告诉我原因吗?

char* cut_command_head(char *my_command, char *character) {
    char command_arg[256];
    //command_arg = (char *)calloc(256, sizeof(char));
    char *special_position;
    int len;
    special_position = strstr(my_command, character);
    //printf("special_position: %s\n", special_position);
    for (int i=1; special_position[i] != '\0'; i++) {
        //printf("spcial_position[%d]: %c\n", i, special_position[i]);
        command_arg[i-1] = special_position[i];
       //printf("command_arg[%d]: %c\n", i-1, command_arg[i-1]);
    }
    len = (int)strlen(command_arg);
    //printf("command_arg len: %d\n", len);
    command_arg[len] = '\0';
    my_command = command_arg;
    printf("my_command: %s\n", my_command);
    return my_command;
}

int main(int argc, const char * argv[]) {
    char *test = "cd xxx";
    char *outcome;
    outcome = cut_command_head(test, " ");
    printf("outcome: %s\n",outcome);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

alk*_*alk 5

这里

my_command = command_arg;
Run Code Online (Sandbox Code Playgroud)

您将局部变量的地址分配给要返回的变量.这个局部变量存在于堆栈中cut_command_head().

返回函数后该地址无效.访问返回的内存cut_command_head()会引发未定义的行为.

你需要在某个地方分配内存.

最简单的方法是使用strdup()(如果可用):

my_command = strdup(command_arg);
Run Code Online (Sandbox Code Playgroud)

使用便携式方法,malloc()然后复制有问题的数据:

my_command = malloc(strlen(command_arg));
if (NULL != my_command)
{
  strcpy(my_command, command_arg); 
}
Run Code Online (Sandbox Code Playgroud)

这看起来很奇怪:

len = (int)strlen(command_arg);
//printf("command_arg len: %d\n", len);
command_arg[len] = '\0';
Run Code Online (Sandbox Code Playgroud)

只需删除它并command_arg在开头就初始化 为全零,以确保它始终被0终止:

char command_arg[256] = {0};
Run Code Online (Sandbox Code Playgroud)