I wrote a word_pattern function as below.
I didn't get a return value, what's wrong with the code?
Below is the codewars training.( https://www.codewars.com/kata/5f3142b3a28d9b002ef58f5e/train/c )
#include <stdlib.h>
#include <string.h> //strlen
#include <ctype.h> //islower
char *word_pattern(const char *word) {
int i, j;
int size = strlen(word) ;
char *ans = (char*)malloc(sizeof(char) * (size * 2 ));
char *base = ans;
if (ans == NULL)
{
return NULL;
}
for (i = 0; i < size; i++)
{
if (i == 0)
{
*ans++ = (char)i;
*ans++ = '.';
/*break;*/ continue;
}
for (j = 0; j < i; j++)
{
if ( islower(word[i]) == islower(word[j]) )
{
*ans++ = (char)j;
*ans++ = '.';
break;
}
}
if(j == i)
{
*ans++ = (char)i;
*ans++ = '.';
}
}
*--ans = '\0';
return base;
}
I didn't get a return value, what's wrong with the code?
Below code sets ans[0]
to 0, the null character .
if (i == 0) {
*ans++ = (char)i;
Printing the return pointer as a string prints nothing as the string ends immediately.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.