This seems simple but I'm new to C and can't find anyone asking this online. I have a char[] that I set with sprintf. Then I need to make a const char* from that char[]. Is that possible or do I need to play around with my types? I need a const char* to enter into a MySQL query, but I need the char[] because I need to use sprintf to insert variable values into the result. Here is the code snippet:
char sqlbuff[4096];
const char* sqlquery;
sprintf(sqlbuff, " %s %s ",
"SELECT idnum FROM idTbl WHERE idCol =", idVar);
sqlquery = &sqlbuff;
if ( mysql_query(con, sqlquery) )
{
finish_with_error(con);
}
I've tried setting the const char variable in multiple ways, but I always get an error. If I hardcode a value for idVar and simply run
mysql_query(con, "SELECT idnum FROM idTbl WHERE idCol = 1300)
it works fine. The problem is I need to use sprintf to utilize the variable. All help is appreciated.
Edit: Running on HP-UX 11.11
From your code sample, it seems that what you mean is that you want a
const char *that points to the contents of yourchar[]. That's devastatingly easy:This is because values of array type are automatically converted to pointers in almost all expression contexts, and because it is allowed to assign a value of non-
consttype to a variable of the correspondingconst-qualified type.Moreover, for what you show, you don't even need the variable. You can just specify the identifier of the array as the argument to
mysql_query. The same automatic conversion from array to pointer applies here, and you can reasonably interpret theconstqualifier in the type of its second argument as a promise that that function will not try to modify the pointed-to data.:On the other hand, your attempt,
, generates a pointer of the wrong type.
&sqlbufis a pointer to an array, whereassqlqueryis declared to be a pointer to a char. A pointer to the firstcharof achar[]will point to the same place as a pointer to the whole array, but the two have different types.