为什么 strcmp() 不比较 chararray 和 char?

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

我正在 PicoC 中编写一个小脚本来获取我的 Loxone Miniserver Go 的公共 IP 地址。所以我总是知道我的公共IP。我的计划是获取 IP,将其分成 4 个部分,并将整数设置为程序输出。

这是脚本

// write program here in PicoC

char* append(char* addThis, char* toThis)
{
    char* destination = (char*)malloc( strlen( addThis ) + strlen( toThis ) + 1 );
    strcpy( destination, toThis );
    strcat( destination, addThis );
    return destination;
} 

while(TRUE)
{
    char *result = NULL;
    result = httpget("checkip.dyndns.org","");
    int j = 0;
    char* p = NULL;
    p = strstrskip(result,"Current IP Address: ");
    j=strfind(p, "<", FALSE);
    char ip[strlen(p)-j];
    strncpy(ip,p,j);
    char *first = malloc(4);
    char *second = malloc(4);
    char *third = malloc(4);
    char *fourth = malloc(4);
    char *tmp = NULL;
    for (int i = 0; ip[i] != '\0'; i++) {    //Made by me, so it may not be the most efficienet way
        tmp = malloc(4);
        if (strcmp(ip[i], ".") || ip[i] != '\0')       //Error
            tmp = append(tmp, &ip[i]);
        if (strcmp(ip[i], ".") && first == NULL) {     //Error
            setlogtext("testing");
            setlogtext(tmp);
            strcpy(frist, tmp);
            setlogtext(first);
        } else if (strcmp(ip[i], ".") && second == NULL) {  //Error
            strcpy(second, tmp);    
        } else if (strcmp(ip[i], ".") && third == NULL) {   //Error
            strcpy(third, tmp); 
        } else if (strcmp(ip[i], ".") && fourth == NULL) {  //Error
            strcpy(fourth, tmp);    
        }
        if (strcmp(ip[i], ".") || ip[i] == '\0')
            free(tmp);
    }
    free(tmp);
    setlogtext(first);
    setoutput(0, atoi(first));
    setoutput(1, atoi(second));
    setoutput(2, atoi(third));
    setoutput(3, atoi(fourth));
    sleeps(15);
}

我也已经阅读了文档,但我无法解决这个问题。

谁能帮我解决这个问题吗?

strcmp picoc loxone-miniserver
1个回答
1
投票

我不了解 PicoC,但我想这里的问题与 C 中的问题相同。

strcmp 比较字符串,就是这样。比较 string 和 char 没有意义:要么你的 string 是 1 个字符的长度,在这种情况下你应该直接比较 chars ;或者你的字符串长度不是 1 个字符,在这种情况下它不会等于该字符。

在您的具体情况下,您应该只比较字符,而不是字符串:

if (ip[i] != '.' || ip[i] != '\0')
© www.soinside.com 2019 - 2024. All rights reserved.