Reputation: 113
I'm trying to convert a stack into a string. The function I have is
int StackToString(const struct Stack *stack, char *result, int resultSize);
I want my stack to look like
If there is enough space in the result, the string should be stored there and I want to return with a "1" value. If there isn't (dictated by resultSize) then we return 0 and the result is undefined.
So far, this is what I have written:
int StackToString(const struct Stack *stack, char *result, int resultSize){
int i;
char str[20];
sprintf(str, "stack[0x%x]:\n", stack);
strcat(result, str);
for(i=0; i<stack->currentItemIndex;i++){
???
}
}
Can anyone offer any advice on what I should do next? I think I need to do a sprint with something and compare the remaining elements in the stack to the resultsize and return under certain but I'm not sure how to implement it....
Upvotes: 0
Views: 229
Reputation: 971
If you can use snprintf()
instead of sprintf()
you can get rid of the intermediate buffer and extra copying. Also this would guarantee that your result buffer will not be overwritten.
int StackToString(const struct Stack *stack, char *result, int resultSize) {
int i;
int n;
n = snprintf(result, resultSize, "stack[0x%x]:\n", stack);
if (n < 0 || n >= resultSize)
return 0;
result += n;
resultSize -= n;
for (i = 0; i < stack->currentItemIndex; i++) {
n = snprintf(result, resultSize, "%d: 0x%x\n", i, stack->items[i]);
if (n < 0 || n >= resultSize)
return 0;
result += n;
resultSize -= n;
}
return 1;
}
Upvotes: 1