Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Char Arrays in C

Tags:

arrays

c

I'm having a peculiar issue with a simple function I created. This function generates a random number between 0-14, it then creates an array using that randomly generated number as the size and fills it with the char 'x'.

The problem I'm having is that when I call the function it will randomly display symbols or numbers after the x's.

I had originally declared the array as size 15, but figured it was the remaining slots that were causing this display issue. However, it still persists after changing the function.

Here's the current function I'm using:

void application()
{
    int randSize, i;

    srand((unsigned)time(NULL));
    randSize = (rand() % 15);

    char array[randSize];
    char *bar = array;

    for(i=0; i< randSize; i++)
            array[i] = 'x';

    printf("%s | ", bar);
}
like image 439
Edaleen Cruz Avatar asked Oct 01 '12 15:10

Edaleen Cruz


1 Answers

Don't you need to end your strings with \0 in C? ) For example:

char array[randSize + 1];
for (i=0; i < randSize; i++)
   array[i] = 'x';
array[i] = '\0';

(updated this because you indeed probably wanted to get a useful part of string of randSize length).

like image 183
raina77ow Avatar answered Nov 15 '22 07:11

raina77ow