0

I'm trying to generate two independent characters arrays. The first one must contain the alphabet in lowercase and the second one, in uppercase. My code works but in the second case, the output contain the two arrays one after the other. Can someone explain me why it does? Thanks

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    char lowcase[26], uppercase[26];
    int i = 0, j = 0;

    for ( ; i < 26; i++)
    {
        lowcase[i] = (char)(i+(int)('a'));
    }

    for ( ; j < 26; j++)
    {
        uppercase[j] = (char)(j+(int)('A'));
    }

    printf("%s\n%s\n", lowcase, uppercase);
}

Here the output :

jharvard@appliance (~/Dropbox/pset2): ./alphabet
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
jharvard@appliance (~/Dropbox/pset2):

  • so your problem is why each of the two arrays does not get printed on its own line? – Kareem Oct 3 '15 at 20:46
2

The problem is simple. You have created two string arrays. Each holds the 26 letter alphabet, one lower case, the other upper case. They are created in sequential memory. In this case, the UC array is first, followed immediately by the lc array.

You then try to print them out as strings, using the base variable (i.e., uppercase and lowcase) as the starting address of the string. When you do this, each will be printed starting at that address, and until the end of string marker \0 is found.

Here's the problem. You didn't put the end of string marker in either array. You should have created the arrays with 27 elements, not 26, and put the end of string marker in the last element of each array.

As it turned out, the first memory address after the second array contains the marker (it's actually all 0 bits), so that serves to terminate a printf of a string. uppercase is stored first, followed by lowcase sequentially in memory, so the lower case alphabet prints as you expect, but then when you try to print the uppercase array as a string, it prints until it hits the end of string marker following lowcase - it prints both strings as one string.

If there had been garbage data left in memory following the second array, it would have just kept printing until it hit a byte with all zeros, or errored out, probably with a seg fault.

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

| improve this answer | |

You must log in to answer this question.

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