gpt4 book ai didi

c - 学校项目分割错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:10 26 4
gpt4 key购买 nike

我需要为学校制作这个程序,但是由于“段错误”(11),我的错误项目被终止了。我相信这与程序中内存不足有关,但我并没有真正看到内存使用量过大的函数。任何帮助将不胜感激。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define _CRT_SECURE_NO_WARNINGS

int STRLEN = 36;



int findOcurrance( char str[], char Char1){
for(int i = 0; i < STRLEN * 3; i++){
if(str[i] == Char1)
return i;
}
return -1;
}

void replaceVowelsA(char str[], char Char) {
for(int i = 0; i < STRLEN * 3; i++) {
int index = findOcurrance(str, Char);
str[index] = 'a';
}
}

void insertaChar(char str[], char Char1, int index){
for(int i = STRLEN * 3; i >= index; i--){
if(i != 0 && (str[i] != '\0' || i == strlen(str))){
str[i] = str[i - 1];
}
else if(i == 0){
str[0] = ' ';
}
}
str[index] = Char1;
}

void adday(char str[]) {
char consonants[42] = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'};
for(int i = 0; i < STRLEN * 3; i++){
if(i==0){
for(int c = 0; c < 42; c++){
if(str[i] == consonants[c]){
insertaChar(str, 'y', i);
insertaChar(str, 'a', i);
break;
}
}
}
else if(i != 0){
if(str[i-1] == ' '){
for(int c = 0; c < 42; c++){
if(str[i] == consonants[c]){
insertaChar(str, 'y', i);
insertaChar(str, 'a', i);
break;
}
}
}
}
}
}

int findWords(char str[]){
int count = 0;
for(int i = 0; i < STRLEN * 3; i++){
char c = str[i];
if(isspace(c))
count++;
if(count == 2)
return i + 1;
}
return -1;
}

char* stringReorder(char str[], int i){
if(i == -1){
return str;
}
else{
char string1[STRLEN];
char string2[STRLEN * 2];
strncpy(string1, str, i);
strncpy(string2, &str[i], strlen(str) - i);
char string[STRLEN * 3];
strcpy(str, string2);
strcat(str, " ");
strcat(str, string1);
return str;
}
}

void main(void) {
char mystring[STRLEN * 3];
printf("** Welcome to the Double Dutch game **\n");
printf("Please enter a string: ");
scanf("%[^\n]s", mystring);
char vowel = 'e';
replaceVowelsA(mystring, vowel);
vowel = 'i';
replaceVowelsA(mystring, vowel);
vowel = 'u';
replaceVowelsA(mystring, vowel);
vowel = 'o';
replaceVowelsA(mystring, vowel);
adday(mystring);
int index = findWords(mystring);
strcpy(mystring, stringReorder(mystring, index));
printf("Double Dutch translation: %s", mystring);
}

最佳答案

在函数 replaceVowelsA() 中,您将输入的字符串替换为特定字符。在函数 replaceVowelsA() 中,您使用 findOcurrace() 查找 Char 是否存在。如果不是则返回-1,但是你没有检查返回值,所以它可能返回-1,在第22行代码中,它可能执行代码str[-1] = 'a',这是一种非常危险的行为。

您的字符串操作还有其他问题,例如您没有检查的终止字符 NULL

如果你使用 gnu 工具链,你可以添加 -g 选项。您也可以使用其他调试方法来查找问题。

关于c - 学校项目分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com