所以我有一堆字符*。本质上,我想弹出该堆栈并将其连接成一个由"/"分隔的长字符串并返回它。但是我不知道如何正确地做到这一点。
我正在尝试在 C 中执行此操作。所以对于我的代码来说,它是这样的。堆栈大小返回堆栈的大小。抱歉,如果它不好,我真的不知道....
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 character.
*output = 0; // strcat needs to know where output ends.
stacknode = test->head;
while(stacknode != NULL) {
strcat(output, stacknode->name);
stacknode = stacknode->nextNode;
}