代码在创建的字符串末尾不断给我 m

标签 c ansi

此代码基本上是获取用户输入的 (a-z) 并将其转换为摩尔斯电码。但是返回字符串的末尾总是有 'm' 试图做数百万的事情来修复它你能看到我做错了什么吗,谢谢。

//Functions
#include "stdafx.h"
#include <ctype.h>

#include <stdio.h>
#include <string.h>
#include <malloc.h> 
void morse(void);   //prototype
int _tmain(int argc, _TCHAR* argv[])
{
    for(;;){
    morse(); // function call
    }
}

void morse(void){

    char *ss= (char*)malloc(110); // allocating dynamic memory
    strcpy(ss, ".-  -...-.-.-.. .   ..-.--. ......  .----.- .-..--  -.  --- .--.--.-.-. ... -   ..- ...-.-- -..--.----..");
    char *pp =(char*)malloc(110);
    int i = 0;
    int n = 0;
    printf("Enter text to convert to morse code: ");
    scanf("%s", pp);
    char *q =(char*)malloc(110);
    while (*pp != '\0'){//intiate while loop
        *pp = *(pp + n); 
        int f = (*pp - 97)*4; //find letters postion in morse code string
        int a = 0;

        while (a != 4) //copy morse code for the letter into new string
        {
            *(q + i) = *(ss + f);
            i++;
            a++;
            f++;
        }
        n++;

    }
    q[i] = '\0';    
    printf("%s", q); //return morse code
    printf("\n");
    free(ss); //free the allocated memory
    free(pp);
    free(q);
    return;
} 

最佳答案

你的循环绕过一个额外的字符。外循环查找 *pp 为\0,但 *pp 仍然是前一个字符的值。

将其更改为:

while (*(pp+n) != '\0') {  // test next character
    char c = *(pp + n);    // fetch next character
    int f = (c - 97)*4;    // find character's index into morse array

我发现它的方法是在调试器下运行并观察发生了什么。尽管我只输入了一个字符,但当它绕过两次循环时,它很快就变得很明显了。使用调试器,这是一个很棒的工具。通过调试器单步执行代码是值得的,即使您认为它在工作。有时你会得到惊喜!

关于代码在创建的字符串末尾不断给我 m,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505127/

相关文章:

c - __builtin_apply 用于在 gcc 中构造调用的大小参数?

c - 在 c 中使用 sendto() 发送自定义 tcp 数据包?

java - 以 ANSI 格式读取和写入文本

javascript - Javascript 无法正确读取 ASCII > 128 的字符

c++ - 有没有办法让windows输出ansi转义序列

c - 与枚举器同名的变量

c - 为什么会出现段错误?

c - popen 创建一个额外的 sh 进程

c - 如何在 ANSI C 中用 NULL 替换字符串中的字符?

emacs - 如何在任何模式下在 emacs 中显示 ANSI 颜色代码?