反转字符串的代码:"Undefined symbols for architecture x86_64"

Code to reverse a string: "Undefined symbols for architecture x86_64"

我正在编写一个函数来反转字符串,但在编译时我一直收到错误 "Undefined symbols for architecture x86_64" (clang)。这是我的代码:

#include <iostream>
#include <string>

using namespace std;

char* reverse(string input);

int main() {
  char* output;
  output = reverse("abcd");
  cout << *output;
}

char* reverse(char* input) {
  char* reversed;
  reversed = new char(sizeof(input) - 1);
  for(int i = 0; i != '[=11=]'; i++) {
    char* j = reversed + sizeof(input - 1);
    input[i] = *j;
    j++;
  }
  return reversed;
}

具体来说,这是编译器打印的内容:

Undefined symbols for architecture x86_64:
  "reverse(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      _main in test-c5860d.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [test] Error 1

我确定我的代码中也存在逻辑错误,但我希望至少在我调试之前对其进行编译和 运行。谢谢!

编译器抱怨

char* reverse(string input);

未定义但

char* reverse(char* input);

是。

不相关的故障。

char* reverse(char* input) {
  char* reversed;
  reversed = new char(sizeof(input) - 1); // <----------- 2 FAULT here
  for(int i = 0; i != '[=12=]'; i++) { // <--- and here
    char* j = reversed + sizeof(input - 1); // <-- and here
    input[i] = *j; // <--- and here
    j++; // <--- and here
  }
  return reversed;
}

应该是

char* reverse(char* input) {
  char* reversed;
  reversed = new char[strlen(input) + 1];  // new array with room for nul
  char* j = input + strlen(input) - 1; // last char in input
  for(int i = 0; input[i] != '[=13=]'; i++) {
    reversed[i] = *j;
    j--;
  }
  reversed[strlen(input)] = '[=13=]';
  return reversed;
}