Hi all, trying to read up on C to get acquainted with the language. Got an exercise am trying to answer and i may need your help to know if am right. I have this code as below, and am asked, what lines have buffer length checking errors.

int main( void ) {
   char[20] in = gets();
   char[20] in2 = gets();
   char[39] out;
   strcpy(out,in);
   int index = strlen(in);
   while(index < 39) {
      out[index] = in2[index-strlen(in)];
      index = index + 1;
       }
       return 0;
     }

From my reading and research so far, line 5 seems to me like the line with an error. My reason is that it does not specify the length to be copied. ( in a lay man's english). I cant say for sure if am right but may need your help and also corrections on the code.

Thanks

Lines 1-4 are all incorrect. You can't declare character arrays like that and you can't use gets() like that. I think you need to pay more careful attention to how those are done. For example

char in[20];

int main( void )
{
    char in[20]; // (string) array of characters - room for 19 plus '\0'
    char in2[20]; // as above
    char out[39]; // array of characters - room for 38 plus '\0'
    int index;


    gets(in); // gets max of 19 characters - if more it will crash!
    gets(in2); // as above and if the sum of both gets' is larger
                // than 38 it will crash 

    strcpy(out,in);
    index = strlen(in);

    // what follows is a peculiar way to append string :-)
    // but it works if string lengths are ok.
    while(index < 39)
        {
        out[index] = in2[index - strlen(in)];
        index = index + 1;
        }
    printf("%s\n", out); // see what the result string is
    return 0;
}

Edited 2 Years Ago by zegarnek

This question has already been answered. Start a new discussion instead.