Home > Back-end >  Codewars problem not passing tests but when I put it into GitHub it does what it's supposed to
Codewars problem not passing tests but when I put it into GitHub it does what it's supposed to

Time:04-21

The instructions for this code wars problem is as follows: link to the problem: https://www.codewars.com/kata/563b74ddd19a3ad462000054/train/c

"write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'.

the string should start with a 1.

a string with size 6 should return :'101010'.

with size 4 should return : '1010'.

with size 12 should return : '101010101010'.

The size will always be positive and will only use whole numbers."

My solution to this problem is as follows.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *stringy (size_t size)
{ 
  char *s = malloc(sizeof(char) * size);
  for(size_t i = 0; i < size ; i  )
{
    if(i % 2 == 0)
      {
      memcpy(&s[i], "1", 1);
    }
  else
    {
      memcpy(&s[i], "0", 1);
    }

}
return s;
}

This passes for numbers 12 and smaller but when they use larger numbers as size to test I will get extra 1's and 0's added to the end and will get an error like

for size = 41, expected: "10101010101010101010101010101010101010101" but got: "1010101010101010101010101010101010101010101010101".

I've put this code into GitHub and made a variable that increments by one for every iteration of the for loop and used printf statements to print the variable just mentioned and the string of 0's and 1's and this works on GitHub with even larger numbers than 41 or anything they would test with on code wars. Is there something wrong with my code or with the test on code wars?

CodePudding user response:

YOu need space for terminating NULL

And then you have to set the NULL at the end

char *stringy (size_t size)
{ 
  char *s = malloc(sizeof(char) * (size 1));  <<<<==========  1
  
   for( size_t i = 0; i < size ; i  )
  {
     if(i % 2 == 0)
      {
        memcpy(&s[i], "1", 1);
      }
     else
     {
        memcpy(&s[i], "0", 1);
      }

  }
   s[size] = '\0'; <<<<=== trailing zero
return s;
}

as other have pointed out, memcpy is a huge overkill here, simpler (and less surprising to readers of the code) is

char *stringy (size_t size)
{ 
  char *s = malloc(sizeof(char) * (size 1));  <<<<==========  1
  for( size_t i = 0; i < size ; i  )
  {
     if(i % 2 == 0)
     {
        s[i] = '1';
     }
     else
     {
        s[i] = '0';
     }
  }
  s[size] = '\0'; <<<<=== trailing zero
  return s;
}
  •  Tags:  
  • c
  • Related