- 论坛徽章:
- 0
|
本人在学习 C 语言的 正则表达式时,参考 http://bbs.chinaunix.net/viewthread.php?tid=303346 文章,在调试文章的实例程序时,做了一些微小的改动,但是有一个奇怪的问题。
代码如下:
- #include <stdio.h>
- #include <sys/types.h>
- #include <regex.h>
- static char* substr(const char *str, unsigned start, unsigned end)
- {
- static char stbuf[256];
- unsigned n = end - start;
- strncpy(stbuf, str + start, n);
- stbuf[n] = 0;
- return stbuf;
- }
- int main(int argc, char *argv[])
- {
- char *pattern;
- int x = 0;
- int z = 0;
- int cflags = REG_EXTENDED;
- int line_num = 0;
- char ebuf[128];
- char inbuf[256];
- regex_t reg;
- const size_t nmatch = 10;
- regmatch_t pmatch[10];
- if (argc < 2)
- return 1;
- pattern = argv[1];
- z = regcomp(®, pattern, cflags);
- if (z != 0)
- {
- regerror(z, ®, ebuf, sizeof(ebuf));
- fprintf(stderr, "%s:pattern '%s' \n", ebuf, pattern);
- return 2;
- }
- while(fgets(inbuf, sizeof(inbuf), stdin))
- {
- line_num++;
- if ((z = strlen(inbuf)) > 0 && inbuf[z-1] == '\n')
- inbuf[z-1]=0;
- z = regexec(®, inbuf, nmatch, pmatch, 0);
- if (z == REG_NOMATCH)
- continue;
- else if (z != 0)
- {
- regerror(z, ®, ebuf, sizeof(ebuf));
- fprintf(stderr, "%s: regcom('%s') \n", ebuf, inbuf);
- return 3;
- }
- for (x = 0; x < nmatch; ++x)
- {
- if (pmatch[x].rm_so == -1)
- continue;
- if (!x)
- printf("%04d: %s \n", line_num, inbuf);
- printf("x=%d\t rm_so=%d\t rm_eo=%d\n", x, pmatch[x].rm_so, pmatch[x].rm_eo);
- printf("x=%d\t",x);
- printf("rm_so=%d\t",pmatch[x].rm_so);
- printf("rm_eo=%d\n",pmatch[x].rm_eo);
- printf(" $%d='%s' \n", x, substr(inbuf, pmatch[x].rm_so, pmatch[x].rm_eo));
- }
- }
- regfree(®);
- return 0;
- }
复制代码
程序的尾部,在输出的部分:
- printf("x=%d\t rm_so=%d\t rm_eo=%d\n", x, pmatch[x].rm_so, pmatch[x].rm_eo);
复制代码
的输出结果和:
- printf("x=%d\t",x);
- printf("rm_so=%d\t",pmatch[x].rm_so);
- printf("rm_eo=%d\n",pmatch[x].rm_eo);
复制代码
的输出结果不一样。第一个的输出结果中,前两个变量的输出结果正常,但是,第三个变量的输出结果,输出的结果为 0 ,实际上 pmatch[x].rm_eo 的值并不为0。
本人在 FreeBSD 6.0-RELEASE 和 FreeBSD 5.3-RELEASE 都试过,结果一样。
GCC 版本分别为:gcc version 3.4.4 和 gcc version 3.4.2
为什么呢?虽然去掉哪个 printf 也不影响程序运行,但是,为什么会为 0 呢?
本人百思不得其解,只好请教CU的各位高手了。
[ 本帖最后由 jeffwu 于 2006-1-2 14:02 编辑 ] |
|