我正在尝试使用strstr函数来查找子串的地址和位置,该子串是2D阵列中的一维数组。编译器没有给出错误,但是程序崩溃了,我想知道它为什么会崩溃以及如何解决它。
#include<stdio.h>
#include<string.h>
int main()
{
char twodarray[][20]={"This is a","2D Array"};
char onedarray[]={"Array"};
char *pa;
int position;
pa=strstr(twodarray[20],onedarray);
printf("%p",pa);
position=(int)pa-(int)onedarray;
printf("%d",position);
}
答案 0 :(得分:3)
它正在崩溃,因为你正在以超出界限的方式访问内存。
pa=strstr(twodarray[20],onedarray);
^
|
here
twodarray
只存储2个维度为20的数组,twodarray[20]
正在尝试
超出最大限制(twodarray[1]
)的访问方式,产生未定义
行为和崩溃是对此的表现。
并在标题中回答您的问题:不,您不能使用strstr
将2D扫描为1D,因为strstr
期望C-String是连续的
以'\0'
结尾的字符序列 - 终止字节。你能做什么
do是在循环中使用strstr
:
for(size_t i = 0; i < sizeof twodarray / sizeof twodarray[0]; ++i)
{
pa = strstr(twodarray[i], onedarray);
...
}
你计算位置的方式是错误的,你必须根据计算
源,而不是目标,因为strstr
返回指向源加上偏移量的指针:
for(size_t i = 0; i < sizeof twodarray / sizeof twodarray[0]; ++i)
{
size_t position;
pa = strstr(twodarray[i], onedarray);
if(pa == NULL)
continue;
position = pa - twodarray[i];
printf("substring '%s' found at position %zu of '%s'\n", onedarray, position, twodarray[i]);
}