C - 字符串到莫尔斯电码程序中的段错误

标签 c pointers

我已经尝试用 C 语言编写一个非常简单的字符串到莫尔斯电码转换器几个小时了,我终于在没有任何警告的情况下编译了它。我是 C 初学者,所以我真的不明白如何修复我的代码。我相信问题应该在于我如何用指针等传递字符串,因为这是我最不理解的部分。我找到了一个关于如何执行此操作的示例,但我仍然无法理解它,并且没有任何与我的类似的特定情况,因为我希望它从参数中读取字符串(所有参数都是字符串/字)。

现在我在尝试运行它时遇到段错误:

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

int to_morse(char *);

int main(int argc, char **argv)
{
    char morse[80];
    char *temp;
    for (int counter = 1; counter < argc; counter++)
    {
        *temp = to_morse(argv[counter]);
        strcat(temp, morse);
        printf("%s", morse);
    }

    return 0;
}

int to_morse(char *str)
{
    char *morse[27] =  {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    char *output;
    char character;

    for (int counter = 0; str[counter] != '\0'; counter++)
    {
        character = toupper(str[counter]);
        strcat(morse[character-'A'], output);
    }

    return *output;
}

我相信这不是使用指针传递字符串的正确方法,但我无法找出正确的方法。我怎样才能让我的代码工作?

注意:我知道这可能在某处有重复。但是,有大量的段错误问题,而且所有这些问题都非常具体,并不涵盖我的场景,所以我找不到一个。

最佳答案

你的代码有很多问题。

首先,strcat 采用 2 个参数 - 目标和源。在您使用它的所有情况下,您都以错误的方式使用它们。

其次,当您希望函数 to_morse 返回 char * 时,它会返回 int。这就是传递指针的方式。

第三,您不会在该函数中为output分配任何内存,因此即使您以正确的方式使用了strcat,您也不会得到任何结果存储摩尔斯电码。当您将未初始化的指针传递给 strcat 时,这也是代码崩溃的地方。

最后,您应该检查您尝试转换为莫尔斯电码的字符是否是字母,否则您将超出数组范围。

您的代码应如下所示。我还对其进行了调整,以便您在每个莫尔斯“字母”之间放置一个空格,否则您将无法分辨一个字母的开头和结尾。

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

char *to_morse(char *);

int main(int argc, char **argv)
{
    char *temp;
    for (int counter = 1; counter < argc; counter++)
    {
        temp = to_morse(argv[counter]);
        printf("%s", temp);
        free(temp); // Always remember to free memory you allocate
    }

    return 0;
}

char *to_morse(char *str)
{
    char *morse[27] =  {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    char *output=malloc((strlen(str)*5)+1); // Always remember to allocate 1 more char than you need to store the NUL terminate when allocating memory for strings.
    output[0] = '\0'; // strcat need a null terminator in the string.
    char character;

    for (int counter = 0; str[counter] != '\0'; counter++)
    {
        if(isalpha(str[counter]))
        {
            character = toupper(str[counter]);
            strcat(output,morse[character-'A']);
            strcat(output," ");
        }
    }

    return output;
}

关于C - 字符串到莫尔斯电码程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188042/

相关文章:

c - C (linux) 中的线程

c - 如何忽略c文件中的字符并仅读取整数

c - Hackerrank 挑战超时

c++ - 函数结构指向其他结构的其他函数

c - 在 C 函数中将结构指针设置为 NULL

c - BST 中的中序遍历

c - 警告 : assignment from incompatible pointer type [enabled by default]

c - 从不兼容的指针类型传递参数 1 of ""

c++ - 创建对取消引用指针的引用?

c - 二指针表示困境