Your statement
char charPin[] = ("PIN%d",pin);
is attempting to initialize an unspecified-length array of char
with the expression ("PIN%d",pin)
. That expression looks Pythonesque, but it is syntactically valid in C: the parentheses perform their ordinary grouping function around an expression involving the comma (,
) operator. Evaluated in a context that actually allows that expression, the result would have the same type and value as pin
. That's not at all what you intend, and luckily the problem is of a type that the compiler rejects, as opposed to the one for which the compiler generates code to do the unintended thing you actually told it to do.
The initializer for an array of char
can take either of two forms:
- a string or UTF-8 literal, or
- a brace-enclosed array of individual elements.
Neither of those suits your purpose, so you'll have to fill the array with your desired contents separately from its declaration. Moreover, that means you'll have to declare an explicit size for your array. You need space for the text part (whose size you know), for the integer part (whose size is variable, within limits), and for a one-byte string terminator.
If you're willing to make the very reasonable assumption that pin
's data type (int
?) is no wider than 64 bits, then 20 characters will be sufficient for the maximum possible 19 decimal digits plus a sign, therefore 24 characters should be enough for the whole string. It's usually best to avoid magic numbers in your code, so you might declare charPin
like so:
#define PIN_BUFFER_SIZE 24
// ...
char charPin[PIN_BUFFER_SIZE];
There are several ways you could fill set the array contents, but the most straightforward way for your case would be to use either sprintf()
or snprintf()
. Suppose we're not entirely confident in our size computation, or that the text part is variable. We might then declare a bit more space in charPin
than we think we'll need, but ultimately we want to ensure that we do not overwrite the bounds of the array. snprintf()
is intended for that purpose:
int result = snprintf(charPin, PIN_BUFFER_SIZE, "PIN%d", pin);
That's the basic answer, but a careful programmer would not leave it at that. Supposing we want to be alerted in the event that our assumption about the needed space was wrong, instead of just letting the data be truncated, we would want to test the function's return value and handle any error that it indicates. We would also want to check for a general error code, as generally we should do for every function call that can signal an error:
if (result >= PIN_BUFFER_SIZE) {
fprintf(stderr, "PIN truncated\n");
exit(EXIT_FAILURE); // or handle it some less-drastic way
} else if (result < 0) {
// should not happen, but we're being thorough
fprintf(stderr, "Internal I/O error\n");
exit(EXIT_FAILURE); // or handle it some less-drastic way
}