[英]printf() statement makes a difference to my return value? - C Programming
I'm experimenting with one of the functions in the K&R C Programming Language book and using pointers to write the strindex function rather than array notation. 我正在尝试使用K&R C编程语言手册中的一个函数,并使用指针来编写strindex函数而不是数组符号。 I have a strange problem that if I include a printf() statement at either of the two points in my code below then the function returns the correct index (6 in this case), but if I leave the printf() statements out then the function returns -1.
我有一个奇怪的问题,如果我在下面的代码中的两个点中包含一个printf()语句,那么该函数返回正确的索引(在这种情况下为6),但是如果我将printf()语句保留,那么函数返回-1。
I really can't see why this should make any difference at all and would be grateful for any clarification. 我真的不明白为什么这应该有任何不同,并且会感激任何澄清。 Here's my code:
这是我的代码:
#include <stdio.h>
int strindex(char *a, char *b) {
char *pa;
char *astart = a;
char *pb = b;
int len;
while(*pb++ != '\0')
len++;
while(*a != '\0') {
pa = a;
pb = b;
for(;*pb != '\0' && *pa == *pb; pa++, pb++)
;
if(len > 0 && *pb == '\0') {
return a - astart;
}
//printf("%c\n", *a);
a++;
}
//printf("%c\n", *a);
return -1;
}
int main() {
char *a = "experiment";
char *b = "me";
printf("index is %d\n", strindex(a, b));
return 0;
}
Many thanks 非常感谢
Joe 乔
The problem is the automatic variable len
. 问题是自动变量
len
。 Since you don't initialize it, it starts with a indeterminate (garbage) value. 由于您没有初始化它,因此它以不确定(垃圾)值开头。 Then you increment it, so it will end up as 'garbage + length of b'.
然后你递增它,所以它最终会变成'垃圾+长度为b'。 Any single change to the compiled code, like an extra
printf
call can change the starting value of len
and thus change the behaviour of your program. 对编译代码的任何单个更改(如额外的
printf
调用)都可以更改len
的起始值,从而更改程序的行为。
The solution: int len = 0;
解决方案:
int len = 0;
, and see if you can get more warnings from your compiler. ,看看你是否可以从编译器获得更多警告。 If you are using
gcc
, use the -O -Wall -Wextra
flags. 如果您使用的是
gcc
,请使用-O -Wall -Wextra
标志。 Then you should get a warning like: 然后你应该得到一个警告:
strindex.c:8: warning: 'len' may be used uninitialized in this function
strindex.c:8:警告:'len'可能在此函数中未初始化使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.