[英]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.