2

I am passing an string or a char array to a function and swapping them but losing the first char array's value for some reason. Here is my code:

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;
}

So in foo the function gets passed two pointers and the are attempted to be swapped. Here is the main function. There may be a problem with the passing of the variable, but the compiler did not give me an issue.

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;
}

The output I am getting is as follows:

A Before: first
B Before: last

A After: 
B After: first

Now I have tested the values of the strings while in the function during the strcpy's and turns empty after the final strcpy, which means, or at lest I think, that the problem lies within the pointers to the original variables. It could be a chain reaction type of thing where all of the pointers are pointing to the "a" and it confuses the program.

Any help would be appreciated, also why this is happening would be very useful as well.

4

2 回答 2

1

因为您的字符串ab.So 长,所以strcpy不能按预期工作:

strcpy(b, temp);

提示:

  • 使用strncpy代替strcpy
  • 使用 c++字符串而不是 c 样式字符串。然后您可以将它们交换为a.swap(b);
于 2013-09-13T01:32:01.760 回答
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";
}

http://ideone.com/fDvnnH

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

于 2013-09-13T06:23:17.623 回答