7 Dec 07 10:32
I am having a bit of an issue when trying to concatenate strings using char * pointers.
Here is what I need:
I need to add a list of ID's to a string that is a SQL statement so that I can end up with:
SELECT DISTINCT Object_ID FROM Object_Interactions WHERE Object_ID IN ('UUID1', 'UUID2') ORDER BY Object_ID ASC;
Here is what I am doing:
char *id; /* UUID = 32 chars length */
void strappnd(char *dest, char *src)
/* appends one string to another */
while (*src != '\0')
*dest++ = *src++;
*dest = '\0';
char *buffer = NULL;
char *sql = NULL;
int j = 0;
int buffer_size = 0;
int object_count = 0;
object_count = 2; /* this is actually a calculated value... */
/* I have used malloc() and then assigned a value to object_list[j]->id and that was OK */
buffer_size = 32 * object_count + strlen("''") * object_count + strlen(", ") * (object_count - 1) + 1;
buffer = (char *)malloc(buffer_size * sizeof(char)); /* I know about pointer casting issue and malloc without stdlib.h but there is too much code to be changed... */
for (j=0; j<object_count; j++)
/* we must not end the sequence with a comma */
if (j < object_count - 1)
strcat(buffer, "', '");
sql = (char *)malloc((100 + buffer_size + 1) * sizeof(char));
sprintf(sql, "SELECT DISTINCT Object_ID FROM Object_Interactions WHERE Object_ID IN (%s) ORDER BY Object_ID ASC;", buffer);
sql = SELECT DISTINCT Object_ID FROM Object_Interactions WHERE Object_ID IN (UUID1') ORDER BY Object_ID ASC;
I have been trying and searching for a couple of days for all kinds of solutions but I can't seem to find anything and I can't make it work.
Basically the question is how to transform a const char * into a char *. Does simple casting work? Is it safe? What else can I do because
I keep hitting this wall, and I can't use the standard <string.h> functions because most of them expect a char const * as opposed to
char * in one of the arguments.
I have been looking on the Internet and forums, but for most cases strcat is being used and seems to be enough.
I found interesting variations of strcat, but they don't seem to work and I don't have any more time for this. After finding libAPR I even
thought of using it, but I only need one function from this library and plus the application must be portable on Linux, Mac, Windows...
Any help on how to do string concatenation with char * or how to convert const char * to char * would be greatly appreciated.
Other than that, C is just great. :)
Thanks very much.