const char数组名是函数中的const值吗?
发布时间:2020-12-16 09:51:46 所属栏目:百科 来源:网络整理
导读:s在函数中是有效的, void f(char s[]) { s++; // Why it works here?} 但它不是在主要功能时.它连接到我,因为它具有完全相同的数据类型. void main() { char s[] = "abc"; s++; // wrong because it is a const value.} 这是为什么? 解决方法 这是因为函数
s在函数中是有效的,
void f(char s[]) { s++; // Why it works here? } 但它不是在主要功能时.它连接到我,因为它具有完全相同的数据类型. void main() { char s[] = "abc"; s++; // wrong because it is a const value. } 这是为什么? 解决方法
这是因为函数参数s不是字符数组,而是指向字符的指针.您无法将数组传递给函数.实际传递的是指向数组第一个元素的指针.在这种意义上,数组不是C语言中的第一类对象.因此,以下两个函数原型是等效的 –
void f(char s[]); // equivalent to void f(char *s); 这意味着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; } 但是,以下语句将s定义为数组并使用字符串文字对其进行初始化. char s[] = "abc"; 数组和指针是不同的类型.数组s绑定到堆栈上分配的内存位置.它不能反弹到不同的内存位置.请注意更改变量值和更改变量名称绑定的内存位置之间的区别.在上面的函数中,您只是更改s的内容,但s本身始终指的是在堆栈上分配的固定内存位置. s++; // in main main函数中的上述语句求值为数组s的基址,即& 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',' '}; // illegal operation because s is an array. // s is bound to a fixed memory location and // cannot be changed. s++; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |