【发布时间】:2017-11-21 02:13:16
【问题描述】:
我做这个程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *str, c;
int x = 0, y = 1;
str = (char*)malloc(sizeof(char));
printf("Inserisci stringa principale : ");
while (c != '\n') {
// read the input from keyboard standard input
c = getc(stdin);
// re-allocate (resize) memory for character read to be stored
str = (char*)realloc(str, y * sizeof(char));
// store read character by making pointer point to c
str[x] = c;
x++;
y++;
}
str[x] = '\0'; // at the end append null character to mark end of string
printf("\nLa stringa inserita : %s", str);
char *sub, b;
int w = 0, z = 1;
sub = (char*)malloc(sizeof(char));
printf("Immetti sottostringa da cercare : ");
while (b != '\n') {
// read the input from keyboard standard input
b = getc(stdin);
// re-allocate (resize) memory for character read to be stored
sub = (char*)realloc(sub, z * sizeof(char));
// store read character by making pointer point to c
sub[w] = b;
w++;
z++;
}
sub[w] = '\0'; // at the end append null character to mark end of string
char *p1, *p2, *p3;
int i=0,j=0,flag=0, occurrences=0;
p1 = str;
p2 = sub;
for(i = 0+1; i<strlen(str); i++)
{
if(*p1 == *p2)
{
p3 = p1;
for(j = 0;j<strlen(sub);j++)
{
if(*p3 == *p2)
{
p3++;p2++;
}
else
break;
}
p2 = sub;
if(j + 1 == strlen(sub))
{
flag = 1;
occurrences = occurrences + 1;
printf("\nnel numero di volte : %d\n",occurrences );
printf("\nSottostringa trovata all'indice : %d\n",i );
}
}
p1++;
}
if(flag==0)
{
printf("Sottostringa non trovata");
}
free(str);
free(sub);
return (0);
}
它在字符串中搜索给定的子字符串,一旦找到就打印找到子字符串的位置和找到它的次数,例如,目前如果我的字符串是 aaooaaoo 并且我的子字符串或输出输出位置, 3 和 7 和最后 2 (即出现的次数) 我需要先获取 2,然后以相反的顺序获取位置,即在这种情况下,应该在 7 之前的 2 旁边打印,然后是 3,你怎么能做吗?
【问题讨论】:
-
这是你的第一个逻辑错误:
getc返回int;您应该效仿并将c声明为int,因为按照目前的情况,您的代码会丢弃有用的信息。也就是说,EOF(无论如何你都忽略了)不是字符值;这是一个失败代码,告诉您“getc无法读取字符”。因此,getc可以返回UCHAR_MAX字符值(更具体地说,这些是转换为int的unsigned char值)和一个错误代码(与字符值不同,是负数)EOF) 的值。 -
您的下一个逻辑错误发生在
getc问题之后的行中:realloc使用size_t作为第二个参数(不可能有负值),但y是int(可以有负值)。如果将y设为size_t,则无需乘以sizeof(char)。考虑str[x],其中x为负数,可能是通过整数溢出条件...您应该对所有数组索引使用size_t,而不是int。
标签: c string loops substring reverse