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));
}
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.