【发布时间】:2018-12-11 07:20:28
【问题描述】:
我正在使用简单的字符串匹配和搜索。
为什么*arr 永远不等于point 尽管它们的值(为什么我)是相同的?我很困惑这是什么原因?它与字符串有关还是有其他原因?任何帮助,将不胜感激。如果问题不清楚,我很抱歉。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int search(char ** arr, int size, char *point);
int main()
{
char *array[5]={0};
char original[50];
char toSearch[50];
char *point;
int size=5, searchIndex,i;
/* Copy a string into the original array */
strcpy(original, "why this is not equal");
/* Copy the first 10 characters of the original array into the newcopy array*/
point = memcpy(toSearch, original, 10);
/*string to search*/
array[2]="why this i";
searchIndex = search(array, size, point);
if(searchIndex == -1)
{
printf("%s does not exists in array \n", point);
} else
printf("%s is found at %d position.", toSearch, searchIndex + 1);
return 0;
}
int search(char ** arr, int size, char *point)
{
int index = 0;
// Pointer to last array element arr[size - 1]
char ** arrEnd = (arr + size - 1);
/* Why *arr!=point is never false,
even when both are giving out same values (why this I)?
*/
while(arr <= arrEnd && *arr!=point)
{
printf("%s == %s", *arr,point);
arr++;
index++;
}
if(arr <= arrEnd)
{
printf("%s after found \n",*arr);
return index;
}
return -1;
}
输出:
(null) == why this i
(null) == why this i
why this i == why this i
(null) == why this i
(null) == why this i
why this i does not exists in array
谢谢
【问题讨论】:
-
你是在问为什么array-of-char类型的变量的地址和你复制到它的字符串字面量的地址不一样?
-
我不得不重新扫描五次才能发现
search()的定义。您的格式几乎似乎旨在隐藏该功能... ;-) 我的错误,但我会修复您的缩进以使其对其他人更容易。 -
不是
*arr != point比较“指针”而不是它指向的字符串吗?你不应该使用字符串比较吗?例如strcmp() -
@Yunnosch 答案已经存在:stackoverflow.com/a/8004250/7477557 但我对 StackOverflow 还是很陌生,不知道如何将此线程标记为已回答。如果你不介意,我让你去做。谢谢。
-
@xdrm-brackets 在问题下方尝试 lgrey 单词“flag”。它应该说类似“...的重复”,如果你点击那里,你可以提供一个链接到问题相同的问题,并有一个接受或赞成的答案。现在就随意做吧。但是,我不相信您提供的链接可以作为此链接的原始链接。