C指针问题

sta*_*rob 3 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
Run Code Online (Sandbox Code Playgroud)

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

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

CB *_*ley 15

c不是指针,它是一个数组.虽然数组的名称在大多数数组上下文中衰减为指针,但您不能将数组名称视为可修改的指针.衰变的结果只是暂时的(技术上是一个右值).

因此,您无法应用于++数组的名称.如果要增加指针,请使用指针:

char *d = c;
Run Code Online (Sandbox Code Playgroud)

  • @Jack Kelly:不,postfix` ++`优先于一元`*`.虽然取消引用是冗余的,但指针正在递增,因为未使用该值. (8认同)
  • 你应该补充一点,`*c ++`正在递增`c [0]`.如果它实际上是一个指针,它应该是`c ++`. (2认同)

Tyl*_*nry 6

首先,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
Run Code Online (Sandbox Code Playgroud)

  • `p_c`和`&c`有不同的类型 - 前者是`char*`,后者是`char(*)[3]`.赋值应该是`p_c =&c [0];`或`p_c = c;` (6认同)