简体   繁体   English

为什么我可以在函数内部而不是在 main 中增加字符数组位置

[英]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?这个函数参数 stringLength(char string[]) 和 stringLength(char *string) 有什么区别,第一个不应该不允许 incrementation(string = string +1) 对下面的代码有注释吗?

#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));
}

That's because s is an array in main , but when you pass it as a parameter in stringLength it decays into a pointer .那是因为smain一个数组,但是当您将它作为stringLength的参数传递时,它会衰减为一个pointer

It means that string is not an array, it is a pointer, which contains the address of s .这意味着string不是数组,它是一个指针,其中包含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有一个页面讨论了 C-Faq 中的 C 数组和指针

From there, I recommend you to read questions:从那里,我建议您阅读以下问题:

  • 6.6 Why you can modify string in stringLength 6.6为什么可以在stringLength修改string
  • 6.7 Why you can't modify s in main 6.7为什么不能修改main s
  • 6.2 I heard char a[] was identical to char *a 6.2我听说char a[]char *a相同
  • 6.3 what is meant by the ``equivalence of pointers and arrays'' in C? 6.3 C 中“指针和数组的等价”是什么意思?
  • 6.4 why are array and pointer declarations interchangeable as function formal parameters? 6.4为什么数组和指针声明可以作为函数形参互换?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM