【问题标题】:What is wrong with the code here, intended at finding ceasers cipher?这里的代码有什么问题,旨在寻找停止者密码?
【发布时间】:2019-05-31 07:30:13
【问题描述】:

我试图将 char 指针类型作为函数的返回类型传递,但没有得到任何输出。代码如下:

#include<stdio.h>
#include<string.h>    
char * decrypt(char* pt)
{
    char*  result=malloc(20);
    while(*pt)
    {
    *result=*pt+3;//incrementing by 3 alphbets and copying in reslult
    pt++;
    result++;
    }
    *result='\0';
    return result;
}

int main()
{
    char plaintext[20];
    scanf("%s",plaintext);//getting input

    char *ct= decrypt(plaintext); //passing to function

    printf("\nCiphertext %s",ct);//printing reslut

}

【问题讨论】:

  • 在 printf 的末尾添加一个 '\n'。此外,您正在泄漏内存。
  • 如果你malloc,别忘了free
  • result 将指向字符串的结尾。
  • 查看malloc()的结果,可能为NULL

标签: c char return


【解决方案1】:

result 将在循环之后指向\0

只需添加临时指针以指向字符串的开头并返回。

char * decrypt(char* pt)
    {
        char*  result=malloc(20);
        char *start = result;

        while(*pt)
        {
           *result=*pt+3;//incrementing by 3 alphbets and copying in reslult
           pt++;
           result++;
        }
        *result='\0';

        return start;
    }

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多