我正在编写一个函数来反转字符串,但是在编译 (clang) 时,我不断收到错误“体系结构 x86_64 的未定义符号”。这是我的代码:
#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 != '\0'; 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 != '\0'; 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] != '\0'; i++) {
reversed[i] = *j;
j--;
}
reversed[strlen(input)] = '\0';
return reversed;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句