【发布时间】:2020-04-22 14:07:07
【问题描述】:
我正在尝试编写一个程序,其中需要系统给定文本的莫尔斯电码。关于将文本转换为莫尔斯电码,我将它们全部写在 main 中(与程序文件本身分开)。现在,我的目标是将它写成一个函数,以便在程序的其他函数中使用它。每当我尝试时,它都会出现分段错误。谁能帮我从头开始构造函数本身?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdint.h>
#include<ctype.h>
#include <time.h>
char * fileName1 = NULL;
char * fileName2 = NULL;
int main(int argc, char * argv[]) {
int n;
for (n = 0; n < argc; n++) {
// printf("Argument %s\n",argv[n]); // prints options delete this in the end,just for debugging
if (strcmp(argv[n], "-text") == 0) {
//text to morsecode
int c, v = 0;
char * str = (char * ) malloc(v);
str = (char * ) realloc(str, (c + strlen(argv[n + 1])));
strcat(str, argv[n + 1]);
strcat(str, " ");
char *alphamorse[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
char *nummorse[]={"-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
int i;
char str1[1000];
i = 0;
while (str[i] != '\0') {
if (str[i] != ' ' && (!isdigit(str[i]))) {
printf("%s ", alphamorse[toupper(str[i]) - 65]);
}
if (str[i] == ' ') {
printf(" ");
}
if (isdigit(str[i]) && str[i] != ' ') {
printf("%s ", nummorse[str[i] - 48]);
}
i++;
}
printf("\n");
// end of text to morsecode
}
if (strcmp(argv[n], "-o") == 0) {
//output = concat(output, argv[n + 1]);
n++;
continue;
}
if (strcmp(argv[n], "--") == 0) {
if (n + 1 <= argc) {
fileName1 = argv[++n];
printf(" fileName1=%s\n", fileName1);
}
if (n + 1 <= argc) {
fileName2 = argv[++n];
printf(" fileName2=%s\n", fileName2);
}
}
}
return 0;
}
【问题讨论】:
-
我假设幻数 65 和 48 旨在表示
A和0。在代码中使用这样的数字而不是'A'和'0'是不好的做法,这不仅是为了便于阅读,而且因为这些值会根据字符集而改变。
标签: c function segmentation-fault main morse-code