Search code examples
c++arraysstringcharacter-encodinggarbage

copying char array into another array gives garbage value


I'm making a simple encryption program on the bases of ascii. below is my code and I'm not sure why I'm getting a garbage value at the end while printing the copied string.

output results

#include <iostream>
#include <conio.h>

using namespace std;

void encrypt(char []);
void convertToAscii(char [], char []);
int main()
{
    char userString [] ="This is a string";
    const int size= sizeof(userString);
    char copyString[size];
    convertToAscii(userString, copyString);
    cout<<copyString;
    _getch();
    return 0;
}

void convertToAscii(char s[], char* cs)
{
    for(int i=0; s[i] != '\0'; i++)
    {
        int x = s[i];
        x= x+3;
        char y= x;
        cs[i]=y;
        cout<< x<<" "<<y<<"\n";
    }
}

Solution

  • Just append the terminating zero to the destination string

    void convertToAscii(char s[], char* cs)
    {
        size_t i = 0;
    
        for(; s[i] != '\0'; i++)
        {
            int x = s[i];
            x= x+3;
            char y= x;
            cs[i]=y;
            cout<< x<<" "<<y<<"\n";
        }
    
        cs[i] = '\0';
    }
    

    Another way is the following

    char * convertToAscii( cosnt char *s, char *cs)
    ^^^^^^                 ^^^^^
    {
        char *p = cs;
    
        for ( ; ( *cs = *s ) != '\0'; ++cs, ++s ) *cs += 3;
    
        return p;  
    }