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 tovoID 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绑定到堆栈上分配的内存位置.它不能反d到不同的内存位置.请注意更改变量值和更改变量名称绑定的内存位置之间的区别.在上面的函数中,您只是更改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++;}总结
以上是内存溢出为你收集整理的const char数组名是函数中的const值吗?全部内容,希望文章能够帮你解决const char数组名是函数中的const值吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)