0

In PSET2 Substitution, to display the results, I'm initializing an empty string with:

    char cyphertext[] = {'\0'};

Populating it with:

// makes the substitution
    for (int i = 0; text[i] != 0 ; i++)
    {
        if (isupper(text[i]))
        {
            cyphertext[i] = text[i] - 'A';
        } else {
            cyphertext[i] = text[i] - 'a';
        }
    }

But when I try to print it with:

printf("cyphertext: %s\n", cyphertext);

I get:

cyphertext: 

            �

I don't know where I'm making a mistake. Am I declaring it wrong? Am I "filling" it wrong? Am I printing it wrong?

1 Answer 1

0

The first problem is the declaration. When a string (a char array) is declared, the space for it is allocated in memory. In this case, it's initialized as containing only the end of string (EOS) marker, "\0", so only one space is allocated to it. Any attempt to insert any string into it will overwrite the physical memory adjacent to it. Instead, if you had declared it with an actual length, like this:

char cyphertext[strlen(something appropriate) +1 ] = {'\0'};

then the right amount of memory would have been allocated.

Next, the code isn't encoding the letters correctly. It's producing non-printable or non-alphanumeric ASCII characters. I suggest that a review of the videos on the encoding should be made.

Also, what will the code do with non-alpha characters like punctuation, numbers or spaces?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thank you so much for your commern Cliff. When I try to declare the string with a variable length, I get this error: error: variable-sized object may not be initialized. I inferred that I couldn't use a variable in the length, so I don't know how I should decalre the size of the cyphertext if I don't know the size of the input text I need to cypher. Jul 27, 2022 at 13:53
  • There's no such thing as a "variable length string" in C. In C, a string, ie, a char array, is immutable. That means that the size can't be changed once it is created. But that doesn't mean that you need to know the length of the string at compile time. The string length only needs to be known at run time. In this case, it's easy. char cyphertext[strlen(text) +1 ] ; Then, either populate it with a strcpy() call or be sure to insert the end of string char in the last position.
    – Cliff B
    Jul 27, 2022 at 22:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .