0

The following code is broken when trying to run due to an issue replacing the character on line 33. Am I replacing the character in the string incorrectly?

The code is designed to encrypt lowercase characters in the *cat string. Each character in code2 is 'mapped' to a character in the same position in code1. The lowercase chars in *cat are replaced with their substituted char from code2.

//Ben Adamson
//v1.0
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>

void code(char *s);

int main()
{
    char *cat = "The cat sat";

    code(cat);

    _getch();
    return 0;
}

void code(char *s)
{
    char code1[] = "abcdefghijklmnopqrstuvwxyz";
    char code2[] = "bpduhijkaltxwmrzfoysvngeqc";
    char *letter;
    unsigned int i, letterpos;

    for(i=0; i<strlen(s); i++)
    {
        if(isalpha(s[i]) && islower(s[i]))
        {
            letter = strchr(code1, s[i]);
            letterpos = (int)(letter - code1);
            s[i] = code2[letterpos];
        }
    }
    printf("New string is %s", s);
}
BenAdamson
  • 625
  • 3
  • 10
  • 19

1 Answers1

1
char *cat = "The cat sat";

Her cat is read only.

s[i] = code2[letterpos];

You need to allocate memory if you need to write to it.

char *cat =  malloc(100);

Better way to do it is:

char *cat = strdup("The cat sat");
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 1
    I would recommend using `char *cat = strdup("The cat sat");` – Klas Lindbäck Nov 14 '14 at 15:45
  • 1
    @KlasLindbäck Yeah in order to fix his issue allocating memory will fix it. – Gopi Nov 14 '14 at 15:47
  • Thanks Gopi & Klas - I took your suggestions into account and the code works, after using Klas' line replacement. One note - the compiler complained that strdup is deprecated so I used _strdup instead. – BenAdamson Nov 14 '14 at 15:48
  • @BenAdamson [¡SO al rescate!](http://stackoverflow.com/questions/7582394/strdup-or-strdup), just use `strdup`. – Maarten Bodewes Nov 14 '14 at 15:59