Quote Originally Posted by laserlight View Post
This is wrong:
Code:
static char t[sizeof(*word)] = "";
word is a pointer to char, so sizeof(*word) is equal to 1. Hence, t is an array of char that is only large enough to store an empty string.

If I understand correctly, you want "Paola!" to result in "P a o l a !" (not "P a o l a!" as your comment indicated). So, with a string of length 6, the result string is of length 6*2-1=11. Hence, I would suggest:
Code:
size_t word_len = strlen(word);
char *result = malloc((word_len > 0) ? (word_len * 2) : 1);
if (word_len == 0)
{
    result[0] = '\0';
    return result;
}
The reason why I don't subtract 1 is that you need to account for the terminating null character. There's no point dealing with an empty string as it differs from the length*2-1 pattern, so I check for it early then return. Of course, the downside of using malloc is that after you return the result, the caller is responsible for freeing the memory, so you shouldn't call it within printf like you're doing now. Rather, store the result in a pointer and then pass that pointer to printf.

There's no problem using two functions. What I am more concerned about is that how you're doing the appending with the second function is inefficient: you compute the length of the current result string, and then you append from there; the same "keep finding the end then appending" happens with strcat. This is a waste of time when you can just keep track of the end of the current result string and append from there. For example:
Code:
for (size_t i = 0; i < word_len; i++)
{
    result[i * 2] = word[i];
    result[i * 2 + 1] = ' ';
}
result[word_len * 2 - 1] = '\0'; // overwrite the last space
Incidentally, this eliminates the reason for the second function.

THX! And I turn my static function into non-static, and it still works! in the future ... can the fact that this function is not static maybe cause a headache?
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


char *split_string(char word[])
{


    size_t word_len = strlen(word);
    char *result = malloc((word_len > 0) ? (word_len * 2) : 1);
    if (word_len == 0)
    {
        result[0] = '\0';
        return result;
    } else
    {
        for (size_t i = 0; i < word_len; i++)
        {
            result[i * 2] = word[i];
            result[i * 2 + 1] = ' ';
        }
        result[word_len * 2 - 1] = '\0';
    }


    return result;
}
 
int main() {
     
    //this will print P a o l a !
    printf("%s", split_string("Paola"));
     
    return EXIT_SUCCESS;
}