gpt4 book ai didi

C 中的字符指针

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:54 25 4
gpt4 key购买 nike

 #include <stdio.h>

int main(void){

char *p = "Hello";
p = "Bye"; //Why is this valid C code? Why no derefencing operator?

int *z;
int x;
*z = x
z* = 2 //Works
z = 2 //Doesn't Work, Why does it work with characters?

char *str[2] = {"Hello","Good Bye"};

print("%s", str[1]); //Prints Good-Bye. WHY no derefrencing operator?
// Why is this valid C code? If I created an array with pointers
// shouldn't the element print the memory address and not the string?
return 0;

}

我的问题在评论中列出。在 gerneal 中,我无法理解字符数组和指针。特别是为什么我可以在没有取消引用运算符的情况下访问它们。

最佳答案

In gerneal I'm having trouble understanding character arrays and pointers.

这对于初级 C 程序员来说很常见。大约在 1985 年,我也有过同样的困惑。

p = "Bye";

由于 p 被声明为 char*,p 只是一个包含 char 的内存地址的变量。上面的赋值将 p 的值设置为常量字符串“Bye”的第一个字符的地址,换句话说就是字母“B”的地址。

z  = 2

z 被声明为 char*,因此您唯一可以分配给它的是 char 的内存地址。不能将 2 赋值给 z,因为 2 不是 char 的地址,它是一个常量整数值。

print("%s", str[1]);

在这种情况下,str 被定义为两个 char* 变量的数组。在您的 print 语句中,您将打印其中的第二个,即字符串“Good Bye”中第一个字符的地址。

关于C 中的字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14330615/

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