copying char array into another array gives garbage value

484 views Asked by At

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";
    }
}
2

There are 2 answers

0
Vlad from Moscow On BEST ANSWER

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;  
}
2
Mark Adelsberger On

In C you have to null-terminate your strings. You recognize that because your convertToAscii() function is looking for the null-terminator in the input; but it's not putting an null-terminator on the output, so methods like cout's operator<< don't know where the value at copyString ends.

Of course in order for the convertToAscii function to null-terminate your string, you need to allocate additional space for '\0' in the caller:

char copyString[size + 1];
//                   ^^^