Why can I increment a char array position inside a function and not in main

天大地大妈咪最大 提交于 2019-11-28 10:56:44

问题


What's the difference between this function parameter stringLength(char string[]) to stringLength(char *string), shouldn't the first one not allow the incrementation(string = string +1) that has a comment on the code below?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int stringLength(char string[]) {
    int length = 0;
    while(*string) {
        string = string + 1; // I can do it here
        length++;
    }
    return length;
}

int main(void){
    char s[] = "HOUSE";
    s = s + 1;  // I can not do it here
    printf("%s\n", s);
    printf("%d\n", stringLength(s));
}

回答1:


That's because s is an array in main, but when you pass it as a parameter in stringLength it decays into a pointer.

It means that string is not an array, it is a pointer, which contains the address of s. The compiler changes it without telling you, so it is equivalent to write the function as:

int stringLength(char *string);

There's a page that talks about C arrays and pointers in the C-Faq

From there, I recommend you to read questions:

  • 6.6 Why you can modify string in stringLength
  • 6.7 Why you can't modify s in main
  • 6.2 I heard char a[] was identical to char *a
  • 6.3 what is meant by the ``equivalence of pointers and arrays'' in C?
  • 6.4 why are array and pointer declarations interchangeable as function formal parameters?


来源:https://stackoverflow.com/questions/20530378/why-can-i-increment-a-char-array-position-inside-a-function-and-not-in-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!