【发布时间】:2020-02-06 12:59:01
【问题描述】:
所以,我开始熟悉 C,此时我正在尝试理解指针。我从here 得到以下代码,但我无法理解,如何从指针中减去字符数组。
#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();
}
指针不只是给定变量/常量的地址吗?当减法发生时,字符数组会自动假设,因为操作是用指针发生的,所以减去它的地址?我在这里有点困惑。
提前致谢。
【问题讨论】:
-
首先,永远不要永远使用
gets。它是a dangerous function,多年前甚至已从 C 规范中删除。使用例如fgets` 代替。 -
因为数组变量保存在内存中的第一个数组元素地址。当减去内存中的两个地址时,您会得到这两个地址之间的位置数
-
我读到了gets的用法,不打算使用它,但我想展示源代码不变的示例
-
我现在明白了,谢谢,还没有考虑过:)
-
请注意
found - s的值是ptrdiff_t类型。ptrdiff_t的正确格式说明符是%td,而不仅仅是%d。请参阅stackoverflow.com/questions/7954439/… 使用错误的格式说明符是undefined behavior 的一种形式。
标签: c arrays pointers implicit-conversion pointer-arithmetic