The code is working as intended
It might seem to be working, but it's not. There are a lot of mistakes in your code.
The worst thing is that you have given buff a size of 1 char. Remember that if you don't specify a size in the square brackets then it takes its size from the initializing string. The string "" only has the terminating '\0' character, and therefore a size of 1. You can't pretend that it's actually 40 if it's really only 1.
You then treat cap in a really strange way. Firstly you erase the value of 40 that it initially had, setting it to 0. Then you do nothing with it except set it to 0 again (using '\0') before the function returns.
What you need to do is to properly size buff, pass in that size, and then use cap to ensure you don't write beyond that size.
Also, checkWord doesn't do anything useful since the strtok function will ensure that there are no spaces in the word.
Little things:
Are you sure you're not supposed to add a space between the words that you append to buff? (Depends on the instructions.)
Don't print buff inside concatenatePalindromes. Print it in main after concatenatePalindromes returns.
There's no reason to use unsigned for boolean return values. Use int, or include <stdbool.h> and use bool.
Don't test a bool value against 1 or 0 (or true or false). Just test it. I.e.:
Code:
// Don't do this:
if (checkPalindrome(word) == 1)
// Do this instead:
if (checkPalindrome(word))
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
bool checkPalindrome(const char *str)
{
int l = 0, h = (int)strlen(str) - 1;
while (h > l)
if (str[l++] != str[h--])
return false;
return true;
}
void concatenatePalindromes(char *s, char *buff, int cap)
{
buff[0] = '\0'; // ensure buff starts empty and zero-terminated
char *word = strtok(s, " ");
while (word)
{
if (checkPalindrome(word))
{
int len = strlen(word);
if (len + 1 > cap) // +1 for '\0'
{
printf("string overflow\n");
return;
}
cap -= len;
strcat(buff, word);
}
word = strtok(NULL, " ");
}
}
int main()
{
char s[] = "ana john michael hannah ana stacy";
char buff[100]; //anahannahana
concatenatePalindromes(s, buff, sizeof buff);
printf("%s\n", buff);
return 0;
}