1

I am new to c programming and would like to write a program which has the following requirement:

Input: The number of inputs n, then n input chars , for example, 3 welcome to hku

Output concatenated chars, for example, welcomehku

However, I discovered a problem that when I submit the codes as following to the c autochecking platform, the output is ~~~~welcometohku instead of welcometohku.

Would anyone like to give help on the issue? Thank you very much to all of you.

#include<stdio.h>
#include<string.h>

int main(){

    int num;  /* array with 50 elements */
    int i = 0;
    char iarray1[100];
    /* read array */
    scanf("%d", &num);

    char iarray[num][100];

    for (i = 0; i < num; i++) {

        scanf("%s", iarray[i]);
    }   

    /* print array elements in reverse order */
    for (i = 0; i < num; i++) {

        strcat(iarray1,iarray[i]);
    }

    //display the concatenated string
    printf("%s",iarray1);
    return 0;
}
Chun Tsz
  • 55
  • 2

1 Answers1

1

You need to initialize iarray1

Try

char iarray1[100] = {0};

The reason is that an uninitialized iarray1 may contain any value. So when you do the first strcat it may happen the string you want to concatenate is appended to some gargabe value.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • May I ask why I need to initialize? I thought declaration of array with its size is enough when using c++? – Chun Tsz Dec 07 '18 at 12:45