I’m new to C and am having trouble with strings. What I would like to do is create a string like “val1, val2, val3” in a loop.
Currently my code looks something like:
char tagstr[60] = "";
int k;
int n = 5;
for (k=0; k < n; k++) {
char temp[10] = "";
sprintf(temp, ", val%d", k);
strcat(tagstr, temp);
}
But the output of tagstr is “, val#”, where # is some long integer value. I’m guessing I’m doing something wrong with pointers here but I’ve tried everything I can think of without success… any help would be much appreciated.
EDIT: more context, if it helps:
int tagsClosed = strlen(pch1) - strcspn(pch1, ")");
do {
if (curTag.size > 0) {
// problem section
char tagstr[60] = "";
int k;
for (k = 0; k < 5; k++) {
char temp[10] = "";
sprintf(temp, ", val%i", temp, k);
strcat(tagstr, temp);
}
// This prints out something like ", val-890132840" x 5 (same number)
printf ("String is now: %s\n", tagstr);
}
curTag = *(curTag.parent);
tagsClosed--;
} while (tagsClosed > 0);
curTag is a struct:
typedef struct Tag {
char * name;
int size; // number of children
int tagnum;
struct Tag* parent;
} Tag;
The problem is that
sprintf(temp, ", val%i", temp, k);adds the value oftemp(which is actually the address of the first character in the array) to the string, and doesn’t add the value ofkto the string at all. This should besprintf(temp, ", val%i", k);.You can calculate the amount of space you’d need in advance (including zero terminator):
Also; using
strcatis bad (for performance) because you’d be repeatedly searching for the end of thetagstrand then copying the new characters to the end. It would be better to keep track of the current end oftagstrand store then next group of characters directly at the end with no searching, no temporary string and no copying. For example: