#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * odd(const char * S, char * dest);
int main()
{
char * source = "abcdefghijklmnopacegiacegi";
unsigned int length = strlen(source);
char dest[length];
printf("%s\n",odd(source, dest));
}
char * odd(const char * source, char * dest)
{
int count = 0;
unsigned int length = strlen(source);
for(int i = 0; i < length; i++)
{
if( (source[i] %2 )!= 0)
{
dest[count] = source[i];
count++;
}
}
return dest;
}
the size of dest increases and produces garbage for any values after the length of source
You have to manually include the ending
\0to the string, that is, at the end ofadd, you have to add:You know, the length of strings in C is accounted searching for the
\0character. You have to include one of those at the end of each C string. If not, the string may contain any garbage till the first\0that will be printed.Finally, when creating
dest, you have also to increase the length of the reserved space in one to accomodate that ending 0 character. Thestrlendoes not count that ending 0 character.