C程序的功能似乎总是如此,但我不明白为什么

时间:2014-08-28 20:19:57

标签: c arrays if-statement boolean

(我是Stackoverflow的新手。)

我目前正在使用C的正则表达式引擎,但是存在一些问题。

第一个函数叫做“contains”。如果你将两个char数组传递给那个func,一个是源,另一个是你在该文本中寻找的针,如果文本包含片段,它将返回true,否则返回false(如果不包含) needle数组有更多元素作为文本数组。)

我用gcc编译:

gcc -std=c99 test.c regex.c -o test

./测试

即使针的长度较大,也始终打印“包含”。

一个片段:

bool contains(const char source[], const char needle[]){

unsigned int source_length = (int)sizeof(source)/sizeof(source[0]);
unsigned int needle_length = (int)sizeof(needle)/sizeof(needle[0]);

if(source_length < needle_length) return false; // this should return false to the test program but it doesn't. What's wrong?

}

我认为我只是看不出有什么不对。有人可以帮帮我吗?

谢谢。

尼克

4 个答案:

答案 0 :(得分:3)

T t[]作为函数参数与T*相同。在您的示例中,sourceneedle都是const char*,因此两者的大小相同。因此,测试总是失败。您可以通过打印sizeof(source)sizeof(needle)来轻松检查这一点。

如果指针指向nul终止的字符串,则可以使用strlen获取其长度。否则,您需要传递长度为单独的函数参数。

顺便说一句,请注意您需要在所有情况下都返回一些东西。测试失败时你没有回来。

答案 1 :(得分:1)

您将指针的大小除以单个字符的大小。它们都是恒定长度,所以它总是返回true。

具体来说,在我工作过的操作系统上,

sizeof(source) // size of const char* == size of pointer to char == 4
sizeof(needle) // size of const char* == size of pointer to char == 4
sizeof(source[0]) // size of char == 1 
sizeof(neeedle[0]) // size of char == 1 

答案 2 :(得分:1)

此功能声明

bool contains(const char source[], const char needle[]);

相当于

bool contains(const char *source, const char *needle);

所以在函数表达式

unsigned int source_length = (int)sizeof(source)/sizeof(source[0]);
unsigned int needle_length = (int)sizeof(needle)/sizeof(needle[0]);

相当于

unsigned int source_length = (int)sizeof( const char * )/sizeof( const char );
unsigned int needle_length = (int)sizeof( const char * )/sizeof( const char );

并且两者都等于sizeof( const char * ),因为sizeof( const char )等于1.

您必须使用标准C函数strlen来比较字符串的长度。

例如

bool contains(const char source[], const char needle[])
{
   return ( !( strlen( source ) < strlen( needle ) ) );
}

答案 3 :(得分:0)

在C中,数组通过引用传递给函数而不是值。这意味着该函数只能看到指向第一个元素的指针,并且不知道最初分配了多少空间。您必须手动计算元素数量 - 通过迭代每个元素直到获得NULL字符。

您可以使用辅助功能,例如strlen,但如果您对导入其他库不利,请尝试以下代码:

bool contains(const char source[], const char needle[])
{
  unsigned int source_length = 0;
  unsigned int needle_length = 0;
  while(source[source_length++] != '\0');
  while(needle[needle_length++] != '\0');
  return !(source_length < needle_length);
}

请注意,如果字符串已在contains()内分配,而不是作为参数传递给函数,那么您的解决方案将起作用。