弹出一堆char *来创建一个新字符串并返回它

时间:2014-11-25 05:06:10

标签: c string stack malloc concatenation

所以我有一堆char *。基本上我想弹出该堆栈并将其连接成一个由“/”分隔的长字符串并返回它。但是我不知道如何正确地做到这一点。

我想在C中这样做。所以对我的代码来说就像这样。 Stacksize返回堆栈的大小。道歉如果不好,我真的没有线索......

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;

非常感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:1)

stacksize函数是否返回连接字符串的总长度或堆栈中元素的数量?

如果它返回堆栈中char *指针的数量,则需要预先分配连接字符串的总大小:

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;
}