C 操纵字符串(切割字符串的头部)
为什么我不能得到“xxx”?返回的值是一些非常奇怪的符号。。。我希望返回的值是xxx,但我不知道这个程序有什么问题。该函数运行良好,可以为我打印“xxx”,但一旦它向主函数返回值,字符串结果就不能很好地显示“xxx”。谁能告诉我原因吗C 操纵字符串(切割字符串的头部),c,C,为什么我不能得到“xxx”?返回的值是一些非常奇怪的符号。。。我希望返回的值是xxx,但我不知道这个程序有什么问题。该函数运行良好,可以为我打印“xxx”,但一旦它向主函数返回值,字符串结果就不能很好地显示“xxx”。谁能告诉我原因吗 char* cut_command_head(char *my_command, char *character) { char command_arg[256]; //command_arg = (char *)calloc(256, sizeo
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;
}
这里
将局部变量的地址分配给要返回的变量。此局部变量位于cut\u command\u head()
的堆栈上
函数返回后,此地址无效。访问cut\u command\u head()
返回的内存会引发未定义的行为
你需要在某时某地分配内存
最简单的方法是使用(如果可用):
可移植方法是先使用,然后复制相关数据:
my_command = malloc(strlen(command_arg));
if (NULL != my_command)
{
strcpy(my_command, command_arg);
}
这看起来也很奇怪:
len = (int)strlen(command_arg);
//printf("command_arg len: %d\n", len);
command_arg[len] = '\0';
只需将其删除,并在开始处将命令参数初始化为全零,以确保始终以0
终止:
char command_arg[256] = {0};
你使用调试器了吗?设置断点?逐步检查代码?将实际变量值与预期值进行比较?类似于“{???{?”…您也可以运行此代码。通过使用alk的方法,新结果是正确的。
len = (int)strlen(command_arg);
//printf("command_arg len: %d\n", len);
command_arg[len] = '\0';
char command_arg[256] = {0};