I am really getting confused on how pointers work. I am trying to write short little programs that will illuminate exactly how they work and I am having some troubles. For example:
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
Obviously this code is not correct, or else I wouldn’t be polling the forum 🙂
I am just having some troubles understanding this from a book, can anyone briefly explain the concept?
First of all,
chere is not a pointer, it’s an array. Arrays can in some contexts be used like pointers, but they are not the same thing. In particular, you can use*c(as if it were a pointer) to access the value in the first position, but sincecis not really a pointer, you can’t change wherecpoints by usingc++.Second, you are misunderstanding what
*means. It’s not just a decoration you use when using pointers. As an operator, it means “dereference”, i.e. give me access to what is being pointed to. Therefore when you are manipulating the pointer itself (by, for example, incrementing it) and not manipulating the pointed-to data, you need not use it.Here is what you probably wanted: