c - 如何从指针中减去字符数组?
问题描述
所以,我开始熟悉 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();
}
指针不只是给定变量/常量的地址吗?当减法发生时,字符数组会自动假设,因为操作是用指针发生的,所以减去它的地址?我在这里有点困惑。
提前致谢。
解决方案
假设您想知道表达式found-s
,那么发生的事情是您减去两个指针。
数组自然衰减为指向其第一个元素的指针。这意味着 plains
等于&s[0]
,这就是这里发生的事情:found-s
等于found - (&s[0])
。
减法之所以有效,是因为found
它指向数组中的一个元素s
,所以指针是相关的(这是指针减法的要求)。结果是两个指针之间的差异(以元素为单位)。
推荐阅读
- node.js - Morgan 和 Rotating-file-stream:interval 无法正常工作
- javascript - Javascript For循环一次附加相同的元素
- python - GIMP:POC 结果与减去混合模式的 GIMP 不匹配
- go - 请告诉我如何将多数组绑定到结构
- android - 如何解决 Android 上的位图内存泄漏?
- scala - Spark Kafka 到 HDFS 写入器的速度受到限制
- angular - 如何从 Angular 中的 API 获取单行数据
- r - r 按组有条件地删除行
- redis - 我们如何限制用户在 redis-cli 中允许在 Redis 中执行特定命令
- sql - SQL 状态随开始日期和结束日期而变化