gpt4 book ai didi

c - const char 数组名称是函数中的 const 值吗?

转载 作者:太空狗 更新时间:2023-10-29 16:01:44 24 4
gpt4 key购买 nike

s++在函数中是有效的,

void f(char s[]) {
s++; // Why it works here?
}

但它不是在 main 函数中。它连接到我,因为它具有完全相同的数据类型。

void main() {
char s[] = "abc";
s++; // wrong because it is a const value.
}

这是为什么?

最佳答案

那是因为函数参数s不是一个字符数组,而是一个指向字符的指针。您不能将数组传递给函数。实际传递的是指向数组第一个元素的指针。从这个意义上说,数组不是 C 中的一流对象。因此,下面两个函数原型(prototype)是等价的——

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 绑定(bind)到堆栈上分配的内存位置。它不能重新绑定(bind)到不同的内存位置。 请注意更改变量值和更改变量名称绑定(bind)到的内存位置之间的区别。在上面的函数中,您只是更改了s的内容, 但 s 本身始终指代分配在堆栈上的固定内存位置。

s++;  // in main

main 函数中的上述语句计算出数组 s 的基地址,即 &s[0] 及其副作用是改变s的内容。更改 s 的内容意味着将变量 s 绑定(bind)到不同的内存位置,这始终是一个错误。 任何变量在其生命周期内总是指向相同的内存位置。然而,它的内容可以更改,但这是不同的。

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++;
}

关于c - const char 数组名称是函数中的 const 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com