【发布时间】:2023-01-08 03:28:09
【问题描述】:
我有以下函数,给定一个字符串,它应该在其中找到最常见的几个字母并将结果存储在不同的字符串中。 例如 - 对于字符串“ababa”,最常见的一对是“ba”,而对于“excxexd”,它将是“ex”。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void printError(){
printf("Error: please check your input\n");
}
bool isLexicographicallyPreceding(char couple1[], char couple2[])
{
if (strcmp(couple1, couple2)>=0) return true;
return false;
}
void coupleDetector(int length, char word[], char result[])
{
char couples[length-1][2];
for (int i=0; i<length-1; i++)
{
char couple[2] = {word[i], word[i+1]};
strcpy(couples[i], couple);
}
char element[]="";
int count=0;
for (int j=0; j<length-1; j++)
{
char tempElement[2];
strcpy(tempElement,couples[j]);
int tempCount=0;
for (int p=0; p<length-1; p++)
{
if (couples[p]==tempElement) tempCount++;
}
if (tempCount>count)
{
strcpy(element, tempElement);
count=tempCount;
}
if (tempCount==count)
{
if (isLexicographicallyPreceding(tempElement,element) == true) strcpy(element, tempElement);
}
}
strcpy(result,element);
}
int main() {
//Supposed to print "ba" but instead presents "stack smashing detected".
int length=5;
char arr[] = "ababa";
char mostCommonCouple[2];
coupleDetector(length,arr,mostCommonCouple);
printf("%s", mostCommonCouple);
return 0;
}
代码编译没有错误,但由于某种原因没有按预期工作,而是打印出“检测到堆栈粉碎”。为什么会这样?建议会很有帮助。 谢谢。
【问题讨论】:
-
风格说明:自然陈述:
if (boolean_expression) then return true; else return false;可以只是return boolean_expression; -
你把所需的 NUL 终止符放在
char mostCommonCouple[2];的什么地方? -
C 字符串是终止字符序列。你是两个字符的字符串操作不为终止符保留空间。任何关于 C 语言的文本,即使是较差的文本,都涵盖了字符串在 C 中的表示方式和字符串操作的工作方式。
标签: arrays c string pointers stack