简体   繁体   中英

Printing Char Arrays in 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);
}

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).

printf("%s | ", bar);

The %s conversion requires a pointer to a 0-terminated character array, but your array is not 0-terminated. Thus the behaviour is undefined, but what usually happens is that printf continues reading and printing characters until it finds a 0 byte or reaches forbidden memory, causing a segmentation fault, whichever happens first.

%s expects a pointer to a null-terminated string . You're not providing that, so you have undefined behaviour and your program is ill-formed.

Read the formatted manual for printf to see how it works and what it expects. In fact, do this for every library function that you are using in your code. No point doing stuff you're not supposed to do and then wondering why it doesn't work; all good libraries will provide specific descriptions of their requirements.

You're using printf to print a C string. C strings must be null-terminated.

If you want to use array as a string, you'll need to allocate an additional character, and append a \\0 to the end:

char array[randSize + 1];

// loop to fill the array

array[i] = '\0';

Since printf expects a null-terminated string, without that it will continue to print past the bounds of your array, reading memory that isn't part of your array.

How is this compiling with a variable unless it is declared const? This is an old feature of C99 which is not considered standard. Was not allowed in C prior to that and does not work in C++ either

char array[randSize];

The proper way is

char *array = malloc(randSize);

Am i missing some thing here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM