减去两个char指针

时间:2013-06-19 12:48:17

标签: c pointers

我有一个输入缓冲区,其格式为

-----------------------------41184676334

Some Content
More Content



-----------------------------41184676334

More ContenT!!

变量,将存储边界标记----------------------------- 41184676334

我想知道两个边界标记之间的长度

这就是我做的事情

char *temp, *temp1;

temp = strstr(input,boundarymarker);
temp1 = strstr(temp+ strlen(boundarymarker),boundarymarker);

int length = temp1-temp; 

length返回负值。是不是可以减去?如果不是什么是正确的解决方案?它返回的价值是多少?

3 个答案:

答案 0 :(得分:5)

很可能在两个strstr调用之一中找不到边界标记。你可以查看NULL的temp和temp1吗?

答案 1 :(得分:0)

尝试使用strpos查找标记的第一个匹配项,然后使用它来查找第二个匹配项并减去这些结果。

int pos1 = strpos( temp, marker);
int pos2 = strpos( temp + pos1 + strlen(marker), marker );
printf( " %d ", pos2 - pos1);

答案 2 :(得分:0)

取决于您的编译器/标志int可能是也可能不是足够大的存储容器来保存指针差异。

如果您正在使用数字指针值,请使用intptr_t类型。根据定义,它保证足够大以容纳指针值。

#include <stdint.h>

intptr_t length = (intptr_t)temp1 - (intptr_t)temp;