该s++是有效的,当它是一个函数,
void f(char s[]) {
s++; // Why it works here?
}
Run Code Online (Sandbox Code Playgroud)
但它不是在主要功能时.它连接到我,因为它具有完全相同的数据类型.
void main() {
char s[] = "abc";
s++; // wrong because it is a const value.
}
Run Code Online (Sandbox Code Playgroud)
这是为什么?
这是因为函数参数s不是字符数组,而是指向字符的指针.您无法将数组传递给函数.实际传递的是指向数组第一个元素的指针.C从这个意义上说,数组不是一流的对象.因此,以下两个函数原型是等效的 -
void f(char s[]);
// equivalent to
void f(char *s);
Run Code Online (Sandbox Code Playgroud)
这意味着s可以包含任何字符的地址.
void f(char s[]) {
// s is a pointer to a character.
// s++ is fine. evaluates to s and
// makes s point to the next element
// in the buffer s points to.
s++;
return *s;
}
Run Code Online (Sandbox Code Playgroud)
但是,以下语句定义s为数组并使用字符串文字初始化它.
char s[] = "abc";
Run Code Online (Sandbox Code Playgroud)
数组和指针是不同的类型.该数组s绑定到堆栈上分配的内存位置.它不能反弹到不同的内存位置.请注意更改变量值和更改变量名称绑定的内存位置之间的区别.在上面的函数中,您只是更改了内容s,但s它本身总是指在堆栈上分配的固定内存位置.
s++; // in main
Run Code Online (Sandbox Code Playgroud)
main函数中的上述语句求值为数组的基址s,即to &s[0],其副作用是改变内容s.更改内容s意味着将变量绑定s到不同的内存位置,这始终是一个错误.任何变量在其生命周期内始终引用相同的内存位置.然而,它的内容可以改变,但那是不同的.
int main(void) {
// s is an array. Arrays and pointers are
// different types. initialize s with the
// characters in the literal "abc"
char s[] = "abc";
// equivalent to
// char s[] = {'a', 'b', 'c', '\0'};
// illegal operation because s is an array.
// s is bound to a fixed memory location and
// cannot be changed.
s++;
}
Run Code Online (Sandbox Code Playgroud)