首页 > 解决方案 > 如何从指针中减去字符数组?

问题描述

所以,我开始熟悉 C,在这一点上我试图理解指针。我从这里得到了以下代码,但我无法理解,如何从指针中减去字符数组。

#include<stdio.h>
#include<string.h>
#include<conio.h>

main() 
{   
char s[30], t[20];   
char *found; 

/* Entering the main string */   
puts("Enter the first string: ");   
gets(s);

/* Entering the string whose position or index to be displayed */   
puts("Enter the string to be searched: ");   
gets(t);

/*Searching string t in string s */   
found=strstr(s,t);   
if(found)
    printf("Second String is found in the First String at %d position.\n",found-s);    
else
    printf("-1");   
getch(); 
}

指针不只是给定变量/常量的地址吗?当减法发生时,字符数组会自动假设,因为操作是用指针发生的,所以减去它的地址?我在这里有点困惑。

提前致谢。

标签: carrayspointersimplicit-conversionpointer-arithmetic

解决方案


假设您想知道表达式found-s,那么发生的事情是您减去两个指针。

数组自然衰减为指向其第一个元素的指针。这意味着 plains等于&s[0],这就是这里发生的事情:found-s等于found - (&s[0])

减法之所以有效,是因为found它指向数组中的一个元素s,所以指针是相关的(这是指针减法的要求)。结果是两个指针之间的差异(以元素为单位)。


推荐阅读