所以我有一堆字符*。实际上,我想从堆栈中弹出并将其连接成一个由“/”分隔的长字符串,然后返回它。但是我不知道如何正确地做这件事。
我想用C语言来实现这一点,所以对于我的代码来说,就是这样。stack size返回堆栈的大小。抱歉,如果不好,我真的不知道。。。。
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;
任何帮助都非常感谢。谢谢
最佳答案
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;
}