我写了一个简单的函数来执行逆转:
void in_place_reverse(char *str){ if(!str || !(*str)){ return; } char *str_end = str+strlen(str)-1; int temp; while(str < str_end){ temp = *str; *(str++) = *str_end; *(str_end--) = temp; } }我只是想知道为什么当我做这样的事情时:
char str[] = "Reverse me!"; cout << "Original: " << str << endl; in_place_reverse(str); cout << "Reversed: " << str << endl;str没有在函数内部改变。 我问的原因是因为行*(str++)正在递增指向str的指针。 所以我真正要问的是为什么这样的事情没有必要:
char *str_beg = str; char *str_end = str+strlen(str)-1; int temp; while(str_beg < str_end){ temp = *str_beg; *(str_beg++) = *str_end; *(str_end--) = temp; }这样我们实际上并没有改变指向str的第一个位置的指针。
I wrote a simple function to perform in place reversal:
void in_place_reverse(char *str){ if(!str || !(*str)){ return; } char *str_end = str+strlen(str)-1; int temp; while(str < str_end){ temp = *str; *(str++) = *str_end; *(str_end--) = temp; } }I'm just wondering why when I do something like this:
char str[] = "Reverse me!"; cout << "Original: " << str << endl; in_place_reverse(str); cout << "Reversed: " << str << endl;str wasn't changed inside of the function. The reason I ask is because the line *(str++) is incrementing the pointer that points to str. So what I'm really asking is why something like this isn't necessary:
char *str_beg = str; char *str_end = str+strlen(str)-1; int temp; while(str_beg < str_end){ temp = *str_beg; *(str_beg++) = *str_end; *(str_end--) = temp; }So that we're not actually changing the pointer that points to the first position of str.
最满意答案
你实际上是在暗示这一点,因为'str'是通过值传递的(读作:'作为临时变量中的副本')。
为了澄清这一点,没有(分散注意力)指针:考虑
void increment(int x) { x++; } int i = 1; cout << i << endl; increment(i); cout << i << endl;这将两次打印'1'。 在increment例程中看到的x具有与传递的i相同的值 。 但它不是同一个变量i 。 实际上它是i的副本 。 当我们从例程返回时,副本被丢弃。 进一步阅读:如果我们通过引用传递x ,这将是不同的,如下所示:
void increment(int &x) { x++; }You actually are doing this implicitely because 'str' is passed by value (read: 'as a copy in a temporary variable').
To clarify this without the (distracting) pointer: consider
void increment(int x) { x++; } int i = 1; cout << i << endl; increment(i); cout << i << endl;This will print '1' twice. The x that is seen inside the increment routine has the same value like the passed i. But it is not the same variable i. In fact it is a copy of i. When we return from the routine, the copy is discarded. Further reading: This would be different if we'd pass x by reference, like so:
void increment(int &x) { x++; }更多推荐
发布评论