在在线编译器上,该程序在输入 "ABACABA"
时给出了完美的输出,但在 Codeforces 测试中它只是发布了最后一行。在调试时,我发现当使用 strstr()
时,指针 u
指示指向地址 0
。我无法理解为什么该功能在其他在线编译器上有效,但在 Codeforces 上无效。
编辑:好的,感谢@Jeremy Friesner,我发现实际上是 strncpy 无法正常工作,因为现在自定义测试用例编译器为“str”提供了错误的输出。仍然不知道为什么它在两个不同的编译器上会有不同的行为,我应该做些什么改变。
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char *s;
int length=20;
s = (char *) malloc(length*(sizeof(char)));
char c;
int count=0;
while((c=getchar())>='A')
{
if(c<='Z')
{
//cout<<count;
if(length>=count)
{
s = (char *) realloc(s,(length+=10)*sizeof(char));
}
s[count++]=c;
//printf("%p\n",s);
}
else
{
break;
}
}
char *u=s;
int o=1;
//printf("%p\n",s);
while(u)
{
char *str = (char *) malloc(o*sizeof(char));
str = strncpy(str,s,o);
//cout<<str<<endl;
char *t;
u = strstr(s+1,str);
//printf("u %p\n",u);
t=u;
int ct=0;
char *p;
while(t)
{
ct++;
p=t;
t = strstr(t+o,str);
}
ct=ct+1;
//cout<<"here"<<endl;
if(p==(s+count-o))
{
cout<<o<<" "<<ct<<endl;
}
//cout<<ct<<endl;
o++;
}
cout<<count<<" "<<1;
}
最佳答案
如评论中所述,一个主要问题是您在读入字符串后没有以 null 结尾,这会导致奇怪的结果。具体来说,它会导致您调用未定义的行为,这总是一件坏事。 malloc()
分配的内存和realloc()
分配的额外内存不保证归零。
您可以通过添加以下内容来解决问题:
s[count] = '\0';
就在之前:
char *u = s;
严格来说,您还应该检查 malloc()
和 realloc()
的返回值。另外,你不应该使用成语:
x = realloc(x, newsize);
如果 realloc()
失败,您将丢失指向原始数据的指针,因此您已经泄漏了内存。安全的工作方式是:
void *space = realloc(x, newsize);
if (space == 0)
…report error etc…
x = space;
x_size = newsize;
可能还有其他问题;我没有仔细检查每个可能出现的问题的代码。
关于c++ - strstr 在 codeforces 上的 C++ 4.7 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818770/