C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C指针问题大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我真的对指针如何工作感到困惑.我正在尝试编写简短的小程序,这些程序将完全阐明它们的工作方式,并且我遇到了一些麻烦.例如:

char c[3]; //Creates an array of 3 bytes - the first 2 bytes can be used for characters and the 3rd would need to be used for the terminating zero

*c = 'a'; //sets c[0] to 'a'
*c++; //moves the pointer to c[1]
*c = 'b'; //sets c[1] to 'b'
*c++; //moves the pointer to c[2]
*c = '\0' //sets c[2] to the terminating zero

显然这段代码不正确,否则我不会在论坛上投票:)

我只是从一本书中解决这个问题,有人可以简单地解释这个概念吗?

解决方法

首先,这里的c不是指针,它是一个数组.在某些情况下,数组可以像指针一样使用,但它们不是同一个东西.特别是,您可以使用* c(就好像它是一个指针)来访问第一个位置的值,但由于c实际上不是指针,因此您无法使用c更改c指向的位置.

其次,你误解了*的意思.它不仅仅是使用指针时使用的装饰.作为运算符,它意味着“取消引用”,即让我访问所指向的内容.因此,当您操作指针本身(例如,通过递增它)而不操纵指向的数据时,您不需要使用它.

这是你可能想要的:

char c[3]; // Creates an array of 3 bytes - the first 2 bytes can be used for characters 
           // and the 3rd would need to be used for the terminating zero
char* p_c; // Creates a character pointer that we will use to refer into the c array

p_c = &c[0]; // Assign the address of the first element of the c array to the p_c pointer.
             // This Could also be "p_c = c",taking advantage of the fact that in this
             // is one of the circumstances in which an array can be treated as if it were 
             // a pointer to its first element

*p_c = 'a'; //sets c[0] to 'a'
p_c++;      //moves the pointer to c[1] (note no *)
*p_c = 'b'; //sets c[1] to 'b'
p_c++;      //moves the pointer to c[2] (note no *)
*p_c = '\0' //sets c[2] to the terminating zero

大佬总结

以上是大佬教程为你收集整理的C指针问题全部内容,希望文章能够帮你解决C指针问题所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: