-2

我有以下程序

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char line1[30],line2[30],*chp;
puts("Enter line1:");
gets(line1);
puts("Enter Line2");
gets(line2);
chp=strstr(line1,line2);
if(chp)
printf("%s String is present in Given String",line2);
else
printf("%s String is not present in Given String",line2);
getche();
}

我知道 chp 是这个程序中的一个指针,我怀疑 chp 会存储一个内存位置,但是字符串(line2)的内存位置是如何存储在 chp 指针中的,请程序员帮助我理解这个程序。

4

4 回答 4

1

假设用户运行您的程序并输入如下字符串:

 Enter line1:
 StackOverflow
 Enter line2:
 Over

gets() 会将字符串“StackOverflow.com”写入 line1 数组,将字符串“Over”写入 line2 数组。

让我们假设(只是为了讨论)line1 数组位于内存中的地址 0x1000。内存转储(显示内存中每个字节的地址,后跟存储在那里的字符)可能如下所示:

0x1000   S
0x1001   t
0x1002   a
0x1003   c
0x1004   k
0x1005   O
0x1006   v
0x1007   e
0x1008   r
0x1009   f
0x100A   l
0x100B   o
0x100C   w
0x100D   \0  (i.e. the NUL terminator byte that indicates the end of the string)
[and the remaining 16 bytes of the array are undefined garbage, so we'll ignore them]

在这种情况下,strstr() 要做的是在上述数组中查找子字符串“Over”的第一个实例,如果找到,则返回指向该子字符串的第一个字符的指针。所以在这种情况下,strstr() 将返回值 0x1005,因为这是“Over”中“O”字符的内存位置。

如果第一个字符串不包含第二个字符串,strstr() 将改为返回 NULL。

于 2013-08-15T06:15:00.937 回答
1

strstr 函数在 s1 指向的字符串中搜索 s2 指向的字符串。它返回一个指向 s2 的 s1 中第一次出现的指针。

因此它只存储一个内存位置,即在 line1 中找到 line2 的指针,否则为 null..

于 2013-08-15T06:11:12.877 回答
0

好的,所以 strstr 所做的是如果 string2 位于 string1 中的某个位置,它会在 string1 中返回一个指针,指向 string2 第一次出现的位置。该指针是一个字符指针。这意味着它的内存分配是 sizeof(char)。

我假设您不太了解指针,所以我会给您一个快速教程。所以指针是什么,基本上是一个变量,它包含其他东西在内存中的位置。它本质上指向内存中的其他地方。在这种情况下,您的 line1 位于计算机内存中的某个位置,例如计算机地址 0-29。chp 所做的只是存储 0-29 line2 地址范围内的起始位置。因此,如果您的 line1 是“大家好”,而 line2 就在那里。那么 chp 将指向地址 6,这是第 1 行中“there”开始的地方。它只是一个指针,它不包含整个内存。只有 line1 包含字符串的整个内存。指针只指向内存中的一个位置,而不是内存变量本身。这有帮助吗?

于 2013-08-15T06:24:20.927 回答
0
#include <stdio.h>
#include <string.h>
int main()
{
    char line1[30];
    char line2;                 // here is a char  not char []
    char *chp;
    puts("Enter line1:");
    fgets(line1,30,stdin);      // use fgets
    puts("Enter Line2");
    line2 = fgetc(stdin);
    chp=strchr(line1,line2);
    if(chp)
        printf("%s String is present in Given String",chp);
    else
        printf("%s String is not present in Given String",line2);
    return 0;
}
于 2013-08-15T06:38:54.097 回答