Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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
", s);
    printf("%d
", stringLength(s));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...