[英]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 .那是因为
s
是main
一个数组,但是当您将它作为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:从那里,我建议您阅读以下问题:
string
in stringLength
stringLength
修改string
s
in main
main
s
char a[]
was identical to char *a
char a[]
与char *a
相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.