gpt4 book ai didi

c - 我的 C 程序一直崩溃

转载 作者:行者123 更新时间:2023-12-03 15:37:06 25 4
gpt4 key购买 nike

我有这个小程序,我需要用它在字母表中的位置替换我输入的任何字符串,所以 a = 01、b = 02、n = 14、7 = 07 ... 例如,如果我输入 ab36c 作为输出我应该得到 01 02 03 06 03

当我在另一台计算机上编译它时一切正常,现在当我在我的电脑上运行它程序崩溃时,我仍然可以输入我的字符串但是当我按回车键获得结果(输出)时它显示 program.exe 有停止工作。这里有什么问题吗?

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
#include <stdlib.h>
#include <ctype.h>
//#define SIMBOLU_SKAITS 100

int main(){
char text[200];
char *s2;
char simboli[36]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
char morze[36][3]={"01","02","03","04","05","06","07","08","09","10","11","12","13",
"14","15","16","17","18","19","20","21","22","23","24","25","26",
"00","01","02","03","04","05","06","07","08","09"};
int i, j, garums;

gets(text);

garums=strlen(text);

for (i=0;i<=garums;i++){
for (j=0; j<=36;j++)
if( text[i]==simboli[j]){
strcat(s2,morze[j]);
strcat(s2," ");

break;
}
}

puts(s2);

scanf("%c");
}

最佳答案

您执行了 strcat(s2,morze[j]);s2 从未被初始化,因此它很可能指向无效内存,因此导致崩溃。

编辑:

... 和 scanf("%c") 也会崩溃,因为您没有提供参数。你需要:

char c ;
scanf("%c", &c) ;

编辑 2:

这是不使用simbolimorze 数组的版本:

char *outp = s2 ;
for (i = 0; i <= garums; i++)
{
char c = text[i] ;
if (c >= 'a' && c <= 'z')
outp += sprintf(outp, "%02d ", c - 'a' + 1) ;
else if (c >= '0' && c <= '9')
outp += sprintf(outp, "%02d ", c - '0') ;
}

EDIT3

总结:

char *s2 ; 替换为 char s2[200]; 并将 scanf("%c") ; 替换为 scanf("%c", &c) ;

关于c - 我的 C 程序一直崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22560897/

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