c - 我的 C 程序一直崩溃

标签 c crash

我有这个小程序,我需要用它在字母表中的位置替换我输入的任何字符串,所以 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/

相关文章:

将文本文件中的小写字符转换为大写字母,反之亦然

c - 指导我解决这个困惑(用 C 语言进行 CRC16 的文件验证)

c++ - Eclipse错误: Unresolved Inclusion

iPhone:应用程序委托(delegate)中的 NSTimer 无效导致应用程序崩溃

windows - 分析应用程序崩溃的最佳方法

c++ - Busy-waiting和定时器中断在编程中的优缺点是什么?

c++ - 使用静态变量的递归调用的不同输出

android - 使用 Phonegap 在 android 上捕获后使用 FileReader 读取视频文件

ios - UITableView IBOutlet 在 ViewDidLoad 上崩溃,Apple Beta 审查小组不适合我

android - Activity 似乎是在应用程序对象之前创建的