为什么是向前发展的指针不影响外功能? [英] Why is moving pointer forward not affecting outside function?

查看:74
本文介绍了为什么是向前发展的指针不影响外功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的函数计算字符串中的空格:

I have the following function used to count spaces in a string:

int countSpace(char *str) {
        int nSpaces = 0;
        while (*(str) != '\0') {
                if (*(str) == ' ') {
                        nSpaces++;
                }
                str++;
        }
        return nSpaces;
}

我用这个函数是这样的:

I use this function like this:

char a[]="Hello ";
printf("%d", countSpace(a));

我的问题是,当我这样做:的printf(%S,A); ,称countSpace后,这是为什么 A 在最后不指向?我的意思是,我已经递增countSpace函数内部指针,但外面似乎在一开始还是要被人指指点点。这是为什么?

My question is, when I do this: printf("%s", a);, after calling countSpace, why is that a not pointing at the very end? I mean, I have incremented the pointer inside the countSpace function, but outside seems to be pointing at the very beginning still. Why is that?

我知道我做的countSpace函数内* str中的变化会影响外界,所以如果比如我做的:海峡[0] ='P',功能之外的价值将 POLA 。所以,我不明白为什么指针依然指向的一开始,即使里面的功能我已向前迈进。

I know that the changes that I make in *str inside the countSpace function will affect the outside, so that if for example I do: str[0] = 'p', outside of the function the value of a will be pola. So, I don't understand why the pointer is still pointing at the very beginning even though inside the function I have made it move forward.

推荐答案

由于C会按值参数

  int countSpace(char *str)
                      ^^ 
            This pointer is a copy of the pointer you pass in.

首先,你的 STR 变量指向同样的事情,你的指针
传递给你的函数,但里面countSpace()你只是incremeting该指针的本地副本。

Initially, your str variable points to the same thing as the pointer you pass to your function, but inside countSpace() you are just incremeting the local copy of that pointer.

这篇关于为什么是向前发展的指针不影响外功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆