简体   繁体   English

在c中初始化指针的正确方法是什么?

[英]What is the correct way to initialize a pointer in c?

What is the difference between the following initialization of a pointer? 下面的指针初始化有什么区别?

char array_thing[10];

char *char_pointer;

what is the difference of the following initialization? 以下初始化有什么区别?

1.) char_pointer = array_thing;

2.) char_pointer = &array_thing

Is the second initialization even valid? 第二次初始化是否有效?

The second initialization is not valid. 第二次初始化无效。 You need to use: 你需要使用:

char_pointer = array_thing;

or 要么

char_pointer = &array_thing[0];

&array_thing is a pointer to an array (in this case, type char (*)[10] , and you're looking for a pointer to the first element of the array. &array_thing是一个指向数组的指针(在本例中,类型为char (*)[10] ,并且您正在寻找指向数组第一个元素的指针。

请参阅comp.lang.c常见问题,问题6.12: http//c-faq.com/aryptr/aryvsadr.html

Note that there are no initializations at all in the code you posted. 请注意,您发布的代码中根本没有初始化。 That said, you should keep in mind that arrays decay to pointers (a pointer to the first element within the array). 也就是说,你应该记住,数组衰减为指针(指向数组中第一个元素的指针)。 Taking the address of an array is certainly valid, but now you have a (*char)[10] instead of a char* . 获取数组的地址肯定是有效的,但现在你有一个(*char)[10]而不是char*

In the first case, you're setting char_pointer to the first element of array_thing (the address of it, rather). 在第一种情况下,您将char_pointer设置为array_thing的第一个元素(而不是它的地址)。 Using pointer arithmetic will bring you to other elements, as will indexing. 使用指针算法将带您到其他元素,索引也将如此。 For example 例如

char_pointer[3] = 'c';

is the same as 是相同的

char_pointer += 3; char_pointer + = 3; char_pointer = 'c'; char_pointer ='c';

The second example...I don't believe that's valid the way you're doing it. 第二个例子......我不相信你这样做的方式是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 初始化指向struct的指针数组的正确方法是什么? - What is the correct way to initialize an array of pointer to struct? 在 c 中初始化双指针的正确方法是什么 - What is the right way to initialize double pointer in c 在C / C ++中向指针添加1个字节的正确方法是什么? - What's the correct way to add 1 byte to a pointer in C/C++? 在 C/C++ 中声明和使用 FILE * 指针的正确方法是什么? - What is the correct way to declare and use a FILE * pointer in C/C++? 偏移指针的正确方法是什么? - What is the correct way to offset a pointer? 声明指向__far指针的正确方法是什么? - What is the correct way to declare a pointer to a __far pointer? 初始化一个非常大的结构的正确方法是什么? - What is the correct way to initialize a very large struct? 有没有办法初始化指向C中数组的指针(在同一行上) - Is there a way to initialize a pointer to an array in C (on the same line) 从特定地址初始化多维数组指针的正确方法 - correct way to initialize a multidimensional array pointer from a particular address 在Rust中声明可以传递给期望指针的C代码的结构或只是变量的正确方法是什么? - What is the correct way to declare a structure, or just a variable, in Rust that can be passed to C code expecting a pointer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM