2017-07-23 80 views
1

我想查看一个字符串是否等同于一个URL路径。它应该很简单,但strcmp总是返回< 0(-47)。我可能在斜杠上做错了什么。C使用strcmp来检查URL路径

#include <stdio.h> 
#include <string.h> 
#include <stdbool.h> 

int main() 
{ 
    char path[9]; 
    strcpy(path, "/my/path/"); 
    int len = strlen(path); 

    char lastChar[1]; 
    strcpy(lastChar, &path[len - 1]); 
    printf("LAST CHAR SET TO %s\n", lastChar); 

    bool isPageRequest = strcmp(lastChar, "/") == 0; 
    if(isPageRequest) 
    { 
     printf("ITS A PAGE REQUEST\n"); 
    } 

    bool isMyPath = strcmp(path, "/my/path/") == 0; 
    if(isMyPath) 
    { 
     printf("ITS MY PATH PAGE\n"); 
    } 

    return 0; 
} 

我期待ITS MY PATH PAGE打印出来..但它没有。

回答

3

复制最后一个斜杠的数组太短:char lastChar[1];它应该至少有2个大小以接收空终止符。

你实际上并不需要一个数组,只是比较最后一个字符与'/'可以直接完成。

对于path,您有相同的错误,但对于"/my/path/"来说太短了。

超出数组末尾的复制具有未定义的行为,这意味着可能发生任何事情,包括巧合地包括您实际期望的行为。

试试这个修改后的版本:

#include <stdio.h> 
#include <string.h> 
#include <stdbool.h> 

int main(void) { 
    char path[] = "/my/path/"; 
    int len = strlen(path); 
    char lastChar = path[len - 1]; 

    printf("LAST CHAR SET TO %c\n", lastChar); 

    bool isPageRequest = lastChar == '/'; 
    if (isPageRequest) { 
     printf("IT'S A PAGE REQUEST\n"); 
    } 

    bool isMyPath = strcmp(path, "/my/path/") == 0; 
    if (isMyPath) { 
     printf("IT'S MY PATH PAGE\n"); 
    } 
    return 0; 
} 
+0

我明白这一点。我不明白的是为什么这会使代码的其余部分工作.. –

+0

@JDoe .:未定义的行为是不正当的,它可能会让你觉得你修复了一个bug,然后让你想知道如何? – chqrlie