C指针问题
发布时间:2020-12-16 06:47:42 所属栏目:百科 来源:网络整理
导读:我真的对指针如何工作感到困惑.我正在尝试编写简短的小程序,这些程序将完全阐明它们的工作方式,并且我遇到了一些麻烦.例如: 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
我真的对指针如何工作感到困惑.我正在尝试编写简短的小程序,这些程序将完全阐明它们的工作方式,并且我遇到了一些麻烦.例如:
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 = ' ' //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 = ' ' //sets c[2] to the terminating zero (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |