gpt4 book ai didi

在函数返回之间进行选择

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

我写了一个函数,它有两个不同的返回选项:

//function to compare the strings in function3
int compare(char* str, char* dest){
int answer;
int i;
int length;
length = strlen(str);
// int jlength;
// jlength = strlen(dest);
for(i=0; i<length; i++){
if(str[i] == dest[i]){
answer = 1;
}else {
answer = 2;
}
}
return answer;
}

我想稍后使用这个函数,并根据函数返回的内容发生不同的事情。以下是我如何构建它的相关部分:

 //compare the reversed str with the orignal, now stored in dest
compare(str, dest);
int function3answer;
if(compare == 1){
function3answer = 1;
}else{
function3answer = 2;
}
return function3answer;
}

编译时出现错误:

warning: comparison between pointer and integer [enabled by default]

在 1 周围添加单引号没有帮助(而且也不是我真正想要的,因为我没有引用数组的一部分),也没有将它减少到一个等号(这会产生不同的警告)。

非常感谢!

最佳答案

错误

warning: comparison between pointer and integer [enabled by default]

来自这一行:

if(compare == 1){

您尝试将一个函数与一个整数进行比较。

要消除此错误,请使用 compare 更改函数:

void some_function(...) {
//compare the reversed str with the orignal, now stored in dest
int compare_result = compare(str, dest);

int function3answer;

if(compare_result == 1){
function3answer = 1;
}else{
function3answer = 2;
}
return function3answer;
}

现在,compare 函数。您实现它的方式不会像您预期的那样工作:

  • 如果比较 "abc""poc",您将在 for 循环中得到:

    i = 0, str[0] == 'a', dest[0] == 'p' ==> answer = 2
    i = 1, str[0] == 'b', dest[0] == 'o' ==> answer = 2
    i = 2, str[0] == 'c', dest[0] == 'c' ==> answer = 1
    i = 3, going out for loop and returning **1**.
  • 最糟糕的是,如果将 “a long string”“tiny” 进行比较,当 i4.

您可以这样更正 compare 函数:

#define STRING_IDENTICAL 1
#define STRING_DIFFERENT 2

//function to compare the strings in function3
int compare(char* str, char* dest)
{
int answer;
int i;
int length;
length = strlen(str);
int jlength;
jlength = strlen(dest);

if (length != jlength)
{
/* since size are differents, string are differents */
return STRING_DIFFERENT;
}

for(i=0; i<length; i++){
if(str[i] != dest[i]){
/* at least one different character, string are differents */
return STRING_DIFFERENT;
}
}

/* if we reach this point, that means that string are identical */
return STRING_IDENTICAL;
}

关于在函数返回之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823682/

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