C++ 组合两个以零结尾的字符串?

C++ Combining two zero terminated strings?

所以我在做一个问题,我必须连接两个以零结尾的字符串,第一个包含一个单词,第二个是空的,并且是原始数组大小的两倍。我能够使用以下代码使它正常工作

#include <stdio.h>
#include <iostream>

using namespace std;
int main()
{
    char str1[] = "test";
    char str2[(sizeof(str1)-1)*2];

    char *p;
    int count = 0;

    for(p = str1; *p != 0; p++) {
        str2[count] = *p;
        count++;
    }
    cout << str2;
}

但是我必须使用具有以下原型的函数

char *combine(char *a);

所以我尝试了这个

#include <stdio.h>
#include <iostream>

using namespace std;

char *copy_and_reverse(char *a) {


char str2[8];
    int count = 0;
    char* b = str2;

    for(a; *a != 0; a++) {
        str2[count] = *a;
        count++;
    }
    
    return b;
}

int main()
{
    char str1[] = "test";

    char *a;
    a = str1;

    char* b = copy_and_reverse(a);

    for(b; *b != 0; b++) {
        cout << *b;
    }
}

但它不起作用(它正在打印字符串,但在它之后打印了一些随机字符),我对这些指针感到很困惑,有人可以帮我解决这个问题吗?

编辑:这是我要回答的问题

Write a function in C++ that takes as a char * style zero terminated string and returns a char* string twice the length of the input. The first half of the returned string should contain a copy of the contents of the original array. The second half of the string should contain the contents of the original string in reverse order.

The function should have the following prototype:

char *copy_and_reverse(char* a); 

Note: you should not use any library functions (e.g from string.h).

我相信这会满足您的需求:

#include <stdio.h>
#include <stdlib.h>

static char* copy_and_reverse(char* a);

static int strlen(char *c); // self-implemented

int main(void) {

    char *a = "some string";

    char *b = copy_and_reverse(a);

    printf("%s", b);

    free(b);

    return 0;
}


static char* copy_and_reverse(char* a) {

    int n = strlen(a);

    char *b = new char[n * 2 + 1]; // get twice the length of a and one more for [=10=]

    for (int i = 0; i < n; ++i) { // does copying and reversing
        b[i] = a[i];
        b[i+n] = a[n-i-1];
    }

    b[2 * n] = '[=10=]'; // null out last one

    return b;
}

static int strlen(char *c) {
    char *s = c;
    while( *s++ );

    return s-c-1;
}

你的 copy_and_reverse 代码有两个大问题。

  1. 复制输入字符串后,您并未终止结果。这意味着 str2 不是有效的字符串。修正:

        str2[count] = '[=10=]';  // after the loop
    
  2. copy_and_reverse returns 指向局部变量 (str2) 的指针。在函数returns之后,它的所有局部变量都没有了,main正在处理一个无效指针。要解决此问题,请使用静态内存(例如通过将 str2 声明为 static 或使其成为全局变量)或动态内存(使用 new[](或 malloc() 分配存储) ).两种方法都有其缺点。

小东西:

  • variable; 什么都不做(参见 for (a; ...)for (b; ...))。
  • str2 对于最终结果来说不够大。 str1 是 5 个字节长 ('t', 'e', 's', 't', '[=25=]'),所以 char str2[8] 现在就足够了,但最后你想为你的结果分配 length * 2 + 1 个字节。