gpt4 book ai didi

c - 打印一个字符指针……会发生什么?

转载 作者:太空狗 更新时间:2023-10-29 15:21:50 25 4
gpt4 key购买 nike

我是 C 的新手,我有一个关于字符指针及其打印内容的问题。看看:

int main()
{
char *p1="ABCD";
p1="EFG";
printf ("%s",p1);
return 0;
}

它将打印 EFG

现在:

int main()
{
char *p1="ABCD";
//p1="EFG";
printf ("%s",p1);
return 0;
}

它会给你ABCD

我不明白的是 *p1 到底是什么?
它是包含 char 值的地址的数字吗?它是 char 吗?
*p1 现在是什么?为什么是 const

最佳答案

来自 C 标准:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf

EXAMPLE 8 The declaration

char s[] = "abc", t[3] = "abc";
defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals.

This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type ‘‘pointer to char’’ and initializes it to point to an object
with type ‘‘array of char’’ with length 4 whose elements are initialized with a
character string literal. If an attempt is made to use p to modify the contents
of the array, the behavior is undefined.

换句话说:

1) char *p1; 声明了一个指针变量 (p1)。指针 p1 可以更改。

2) char *p1 = "ABCD"; 声明 p1(与“1”相同)并初始化它指向的数据(将其初始化为只读的 5 元素字符数组“ABCD\0”)。

因此您可以更改“p1”指向的地址(您可以将其指向“EFG”,将其分配给 NULL,等等)。但是您不能安全地更改数据本身。如果您尝试覆盖“ABCD”,您可能会遇到“访问冲突”。确切的行为是“未定义的”——任何事情都可能发生。

3) char p2[] = "ABCD"; 声明一个数组变量 (p2)。它分配5个字符,并将数据初始化为“ABCD\0”。

数组是可读写的(你可以改变数组中的数据),但是变量“p2”不能改变(你不能改变p2指向不同的地址——因为它不是指针)。

4) 那么 char *指针和 char 数组 [] 之间的“区别”是什么?这是一个很好的讨论:

http://c-faq.com/aryptr/aryptrequiv.html

关于c - 打印一个字符指针……会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626795/

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