Originally Posted by
django
Now suppose I have an initialized struct, all the members have values. I want to convert to different member values to strings, concatenate them into one string (my message string) do some separators in between etc.
If I now at runtime want to know how large my string should be, how would you figure that out? Or would simply have to know what size the different variables need, add it up and use that as the size of your string?
tabstop is right.... but in C there's always more than one way to skin a cat...
Make an intermediate buffer larger than you can possibly need, use snprintf() to convert your values... the return value will tell you if it worked or not. This is a good case for a function as the buffer can be instantiated in the function and then it will be disposed of when finished...
Code:
struct t_MyStruct
{ int x;
int y;
char *z; }
MyStruct;
char *MakeString(struct t_MyStruct AStruct)
{ char Buffer[501];
if (snprintf(Buffer,500, "X = %d, Y = %d Z = %s", AStruct.x, AStruct.y, AStruct.z) > 0)
return strdup(Buffer);
else
return NULL; }
// call as...
char *String;
String = MakeString(MyStruct);
if (String)
{
// do stuff with String
free(String); }
... The result is a returned pointer to the space allocated by strdup(), which is the exact size of the text, not the entire size of the buffer. If the result string is too big to fit into the buffer, snprintf() returns -1 and the function returns NULL, which is your signal an error has occured and you may need to make that buffer bigger.
Sometimes it helps to think in smaller blobs...