【发布时间】:2017-02-02 15:48:07
【问题描述】:
我是 C 指针的新手,我正在尝试编写一个类似于高级编程语言的 String.IndexOf() 函数的程序。
基于String.indexOf function in C,我已经开始工作了:
int main() {
int index;
char* source = "test string";
char* found = strstr( source, "in" );
if (found != NULL) {
index = found - source;
}
printf("%d\n", index); // prints 8.
return 0;
}
但是当我尝试将其用作函数时,我总是得到 0。(例如,第一个字符串为“Hello World”,然后“World”将打印“0”而不是预期值“6”)。
基本上,标准输入的第一行是“source”(或“haystack”)字符串,接下来的行将是“needle”。
// includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char master[120];
// returns the index of the substring
int substr(char* needle) {
int index;
char* found = strstr( master, needle );
if (found != NULL) {
index = found - needle;
}
printf("%d\n", index);
return index;
}
int main() {
char input[120];
int timesCalled = 0;
while(fgets(input, 120, stdin)) {
timesCalled++;
if (timesCalled == 1) {
strcpy(master, input);
} else {
substr(input);
}
}
if (timesCalled == 0) {
fprintf(stderr, "Master String is empty");
return 1;
}
return 0;
}
这里发生了什么? “master”的指针在设置为全局变量时会改变吗? “输入”的指针作为参数传递时会改变吗?为什么它在程序版本中起作用?
感谢任何输入。
编辑!
我已将strcpy(input, master) 行更改为strcpy(master, input),但仍然得到相同的结果!
【问题讨论】:
-
将代码
fgets一行转换成input。然后它strcpy(尚未初始化)masteroverinput。你预计会发生什么? -
@dxiv 请查看我的编辑 - 我已经交换了
input和master并且仍然得到相同的输出。