我将一个字符串或一个char数组传递给一个函数并交换它们但由于某种原因丢失了第一个char数组的值。这是我的代码:
void foo(char* a, char* b){
char* temp;
temp = new char[strlen(a)+1];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
delete[] temp;
}
所以在foo中,函数会传递两个指针并尝试交换。 这是主要功能。传递变量可能存在问题,但编译器没有给我一个问题。
int main(){
char a[] = "First";
char b[] = "Last";
std::cout << "A Before: "<< a << "\n";
std::cout << "B Before: " << b << "\n\n";
foo(a, b);
std::cout << "A After: "<< a << "\n";
std::cout << "B After: "<< b << "\n\n";
return 0;
}
我得到的输出如下:
A Before: first
B Before: last
A After:
B After: first
现在我已经在strcpy的函数中测试了字符串的值,并在最后的strcpy之后变为空,这意味着,或者至少我认为,问题在于指向原始变量的指针。它可能是一种连锁反应类型的东西,其中所有指针都指向“a”并且它使程序混乱。
任何帮助都会受到赞赏,为什么这种情况发生也会非常有用。
答案 0 :(得分:1)
因为您的字符串a
超过了b
。所以strcpy
无法按预期排列:
strcpy(b, temp);
提示:
答案 1 :(得分:1)
问题是你的数组大小碰巧正在破坏你的堆栈;幸运的是,对你而言,效果只是在a的第一个字符中放置一个空字节,使其成为一个空字符串。
#include <iostream>
#include <string.h>
void foo(char* a, char* b){
char* temp = new char[strlen(a)+1];
strcpy(temp, a);
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
strcpy(a, b);
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
strcpy(b, temp); // this copies 6 bytes to b, which puts a 0 in the first byte of a.
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
delete[] temp;
}
int main() {
char a[] = "First";
char b[] = "Last";
std::cout << "a size is " << sizeof(a) << std::endl;
std::cout << "b size is " << sizeof(b) << std::endl;
std::cout << "address of a[0] is " << (void*)&a[0] << std::endl;
std::cout << "address of b[0] is " << (void*)&b[0] << std::endl;
foo(a, b);
std::cout << "A After: "<< a << "\n";
std::cout << "B After: "<< b << "\n\n";
}
a size is 6
b size is 5
address of a[0] is 0xbfec5caa
address of b[0] is 0xbfec5ca5
temp = First a = First b = Last
temp = First a = Last b = Last
temp = First a = b = First
A After:
B After: First
您可能需要调查std::string
或查看使用std::strncpy