Thread: Strange error with char array initialisation size

  1. #1
    Registered User
    Join Date
    May 2018

    Strange error with char array initialisation size

    Hey, I came across a weird error in a workshop for a comp sci class. C was a new code introduced to us a few weeks ago, so we are still newbies at this. The error I came across was in a basic challenge question they had, where we had to take an input string, and concatenate it multiple times based on how long it was. Basically, if your input was "hey", you would end up with "hhehey".

    So, what I did was to first create two arrays. One to get the input string, and one to store the result from concatenation. Something I noticed was that I was getting unknown characters outputted in the terminal if I initialised my result array to be larger than 344.

    Here is my code

    int main(){
        char input[80];
        char result[370];
        printf("Enter a word or small sentence: ");
        int i;
        for (i=0;i<strlen(input);i++){
        return 0;
    In it's current state, if I compile it, and input "hello" into it, it does this.

    Strange error with char array initialisation size-screenshot-2018-05-22-21-57-27-jpg

    I was able to get it to work fine by decreasing the size that I initialised the result array to. If I set it to 300, it worked without missing a beat. However, I'd really like to understand why this would cause an error.

    If anyone knows why, I would be most grateful If you would be able to pass on that information.

    Thank you.
    Last edited by TheFallen018; 05-22-2018 at 07:03 AM.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    New York, NY
    Your arrays are uninitialized. They both contain garbage characters. You need to initialize all your local variables.
    // ...
    int main(){
        char input[80] = "";
        char result[370] = "";
    This will insure that all chars in both arrays are set to Nul bytes.

    Also your code:
        int i;
        for (i=0;i<strlen(input);i++){
    Should simply be:
    Please check the man page: "man strcat".
    Last edited by rstanley; 05-22-2018 at 07:58 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getting size of int/char array
    By coderplus in forum C Programming
    Replies: 4
    Last Post: 04-21-2012, 04:18 PM
  2. Determining size of array returning strange values?
    By edddo in forum C++ Programming
    Replies: 13
    Last Post: 07-28-2011, 03:37 AM
  3. (char) array initialization, size etc.
    By cnewbie1 in forum C Programming
    Replies: 6
    Last Post: 06-21-2011, 06:08 AM
  4. char array size question, please help!
    By Ash1981 in forum C Programming
    Replies: 4
    Last Post: 01-29-2006, 02:30 AM
  5. strange problem with 2D char array
    By Sargnagel in forum C Programming
    Replies: 2
    Last Post: 05-31-2003, 11:01 AM

Tags for this Thread