Question:

Sprintf as enhanced strcat?

by  |  earlier

0 LIKES UnLike

Is it safe to use sprintf with the destination string used amongst source parameters?

For example, I want to create a function that returns a list as a CSV string.

void csvize(char length, char* data)

{

output[1000];

sprintf(output,"%d",data[0])

for(int i=1; i<char length, i++)

{

sprintf(output,"%s,%d",output,data[i]); // note "output" used twice!

}

do_something_with(output);

}

 Tags:

   Report

1 ANSWERS


  1. Your syntax will be slow, since you copy a string into itself.

    after each step it will grow thus making it slow

    Try this

    void csvize(char length, char* data)

    {

    char output[1000];

    int nPos;

    nPos = sprintf(output,&quot;%d&quot;,data[0])

    for(int i=1; i&lt;char length, i++)

    {

    nPos += sprintf(output + nPos,&quot;,%d&quot;,output,data[i]);}

    }

    do_something_with(output);

    }

    Since sprintf returns the number of characters copied in the buffer.

    You can just add characters at the end of the output string by adding an offset.

    This is faster then strcat, since strcat has to search for the end each time you use that function.

    Bare in mind that the array in the sprintf is used as a pointer to a char buffer with an offset of nPos.

    BTW : your code will produce faulty result when no data is provided, since you assume there is at least 1 element!!!

    BTW 2: it doesn&#039;t make sense to do a sprintf  with %d and then using a char as argument!!????!!!. Compiler will not complain but i guess you know what your doing!!!!

    BTW 3: the output buffer need enough space to hold the data. Since there is no protection. this code can lead to buffer overrun......

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions