1

So I have a stack of char*. Essentially I want to pop off that stack and concatenate it into one long string separated by a "/" and return it. However I dont know how to do this properly.

I am trying to do this in C. So for my code its something like this. Stacksize returns the size of the stack. Apologies if its bad, I really dont have a clue....

struct stack* test = new_stack();
struct stacknode = test->head;
char* output = (char*)malloc(sizeof(char) * stacksize(test));

while(stacknode != NULL){
   strcat(output, stacknode->name);
   stacknode = stacknode->nextNode;
}
  return output;

Any help is greatly appreciated. Thanks

jjamzn
  • 31
  • 2
  • sizeof(char) is defined to be 1, so you can drop that part. – Craig S. Anderson Nov 25 '14 at 05:14
  • Please [do not cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()`. – Sourav Ghosh Nov 25 '14 at 05:24
  • `output` is uninitialized after you malloc it. You should at the very least set `output[0] = '\0'`. Also it's not clear if `stacksize()` is returning the required size since you didn't give us the code for it. – JS1 Nov 25 '14 at 05:27

1 Answers1

1

Does the stacksize function return the total length of the concatenated string or the number of elements in the stack?

In case it returns the number of char* pointers in the stack you need to preallocate the total size of the concatenated string:

struct stack * test = new_stack();
struct stacknode = test->head;
unsigned int totalsize = 0;

while (stacknode != NULL) {
  totalsize += strlen(stacknode->name);
  stacknode = stacknode->nextnode;
}

char* output = malloc(totalsize + 1); // Allow 1 byte for the \0 character.
*output = 0; // strcat needs to know where output ends.
stacknode = test->head;

while(stacknode != NULL) {
  strcat(output, stacknode->name);
  stacknode = stacknode->nextNode;
}
ezorita
  • 126
  • 1
  • 9