gpt4 book ai didi

c - 我刚刚设置的变量中 printf 期间的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:11 26 4
gpt4 key购买 nike

所以当我在以下情况下调用 printf 时,我遇到了段错误。我只是看不出我做错了什么。有任何想法吗?太感谢了。我已经在代码中用注释标记了出现段错误的位置(在第一段代码中)。

...
char* command_to_run;
if(is_command_built_in(exec_args, command_to_run)){
//run built in command
printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
run_built_in_command(exec_args);
}
...

int is_command_built_in(char** args, char* matched_command){
char* built_in_commands[] = {"something", "quit", "hey"};
int size_of_commands_arr = 3;
int i;
//char* command_to_execute;
for(i = 0; i < size_of_commands_arr; i++){
int same = strcmp(args[0], built_in_commands[i]);
if(same == 0){
//they were the same
matched_command = built_in_commands[i];
return 1;
}
}
return 0;
}

最佳答案

您正在按值传递指针 matched_command。因此,调用 is_command_built_in 不会更改它。所以它保留了它的未初始化值。

试试这个:

char* command_to_run;
if(is_command_built_in(exec_args, &command_to_run)){ // Changed this line.
//run built in command
printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
run_built_in_command(exec_args);
}


int is_command_built_in(char** args, char** matched_command){ // Changed this line.
char* built_in_commands[] = {"something", "quit", "hey"};
int size_of_commands_arr = 3;
int i;
//char* command_to_execute;
for(i = 0; i < size_of_commands_arr; i++){
int same = strcmp(args[0], built_in_commands[i]);
if(same == 0){
//they were the same
*matched_command = built_in_commands[i]; // And changed this line.
return 1;
}
}
return 0;
}

关于c - 我刚刚设置的变量中 printf 期间的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592447/

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