Print Char Arrays in C

I had a particular problem with a simple function that I created. This function generates a random number between 0-14, then creates an array using this randomly generated number as a size and fills it with char 'x'.

The problem I am facing is that when I call the function, it will randomly display characters or numbers after x.

I initially declared an array of size 15, but thought these were the remaining slots causing this display problem. 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);
}
+5
source share
5 answers

You do not need to end the lines with \0in C? ) For instance:

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

( , , , randSize).

+5
printf("%s | ", bar);

%s , 0-. , undefined, , printf , 0 , , , .

+2

%s . , undefined, .

printf, , . , , . , , , ; .

+2

printf C. C .

array , \0 :

char array[randSize + 1];

// loop to fill the array

array[i] = '\0';

printf , , , .

+1

, ​​const? C99, . C ++

char array[randSize];

-

char *array = malloc(randSize);

- ?

+1

All Articles