c - 为什么 memcpy 返回的字符串永远不等于数组中存在的相同字符串?

标签 c arrays memcpy

我正在使用简单的字符串匹配和搜索。 为什么 *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

谢谢

最佳答案

我假设您在问为什么字符数组类型变量的地址与您复制到它的字符串文字的地址不同。

这是一个棘手的问题,因为,请原谅我这么说,目前还不清楚是什么让您期望任何变量的地址在复制某些内容后会有所不同。

考虑用相同字符串文字填充的不是一个而是两个不同的 char 数组的示例。

char toSearch1[50];
char toSearch2[50];
char *point1;
char *point2;

point1 = memcpy(toSearch1, original, 10);
point2 = memcpy(toSearch2, original, 10);
/* or, depending on what to you is more convincingly copying the same literal */
point2 = memcpy(toSearch2, toSearch1, 10);

之后,这两个数组仍然是两个不同的字符数组变量,memcpy 返回目标地址,即两个不同数组的地址。
请想象这两个数组现在如何拥有相同的地址。

如果你跟进

strcpy(original1, "is this in one or both arrays?");

然后您会期望这两个数组再次具有不同的地址吗?

如果这不能回答您的问题,那么您对变量的指针和地址的理解与大多数程序员根本不同,我建议您通过查找有关指针和地址的教程来修改它。

(请注意,为了解释您所问的内容,我跳过了检查与数组大小相关的长度的讨论,使用更安全的字符串复制版本,memcpy 没有正确地以 null 终止复制的字符串。所有这些都很重要用于制作可靠的代码,例如 Lundin 正确地提醒我们。)

关于c - 为什么 memcpy 返回的字符串永远不等于数组中存在的相同字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51146749/

相关文章:

c - 并行/组合多个 64 位值的按位排列

c - 声明结构指针时出错

c - 使用 getchar() while 循环;但是,结果有点奇怪

c - 中断阻塞读

c - 替代 memcpy

arrays - 无法返回过滤后的数组

c# - 如何根据用户输入创建数组长度

python - 将 numpy 数组每行移动一个递增的值

c++ - 我怎样才能将原始数组的 memcpy 等效于 std::vector?

c++ - 访问冲突可以是伪装的内存不足错误吗?