Search code examples
cstringfunctioncharreturn

No output generated from C function returning char*


I am quite new to C so my apologies if this is a straight forward problem but I cannot seem to find my error. My code is as follows

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* makeString(char character,int count)
{
    int i;
    char* finalString=malloc(count+1);
    for(i=1;i<=count;i++)
    {
        finalString[i]=character;
    }
    finalString[count]=0;
    return finalString;
}
int main()
{
    char* string=makeString('*',5);
    printf("%s\n",string);
}

I am trying to get an output of the finalString which would be 'character', 'count' number of times. I am not getting any errors or warnings but It is not generating any output. When debugging it runs the loop successfully but does not ever store any character into finalString. Any help appreciated.


Solution

  • As with many programming languages, C uses 0-based indices for arrays. The first element of the character array at finalString is finalString[0], not finalString[1].

    Your for loop should go from 0 to count - 1, instead of from 1 to count. The line:

    for(i = 1; i <= count; i++)
    

    should instead be:

    for(i = 0; i < count; i++)
    

    As your code is now, you have undefined behaviour, because you try to print finalString[0], which is uninitialized. In this case, it seems to be 0 ('\0').


    I've ignored the fact that makeString is missing its closing }, since you say this compiles correctly, I assume that's a pasting error.