当我们在这个函数中反转字符串时,为什么char * str的指针不会改变?(Why doesn't the pointer for the char *str change when we

编程入门 行业动态 更新时间:2024-10-25 22:24:06
当我们在这个函数中反转字符串时,为什么char * str的指针不会改变?(Why doesn't the pointer for the char *str change when we reverse the string in this function?)

我写了一个简单的函数来执行逆转:

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

更多推荐

本文发布于:2023-08-07 06:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在这个   当我们   字符串   指针   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!