![]() |
|
#1
|
|||
|
|||
Basic pointer problemsHey, I'm having trouble understanding pointers and was wondering if someone could help me. In C lecture class we were given this example:
char *p = "hello"; char a[] = "world"; Now we have to state whether the following statement is valid or invalid. If it is valid we need to display the output and if it is not valid we need to state why. *a = *(a + 1); printf("%s\n", a); When I compile it I get an answer of "oorld". What I am having trouble with is the line before the printf. When you do *(a + 1) does it equal just "o" or "orld" (which is what I thought). Also before the two above lines are executed does *a point to "w" or to the whole string "world"? Thanks for any help! |
|
#2
|
|||
|
|||
|
a points to 'w'. thats what arrays do. arrays are basically pointers. if you try printing array a by itself, without the [], you will get the address, and that address will be the address to the first character which is 'w'. The only difference between arrays and pointers is that pointers can be incremented or decremented or can be made to point to some other location, while the array will always point to the address it was assigned when it is defined.
you can do following with char *ptr = "hello": ptr++; now when you print *ptr, you'll get ello. But you can't do it with array: char a[] = "world": a++ is invalid, however if you want to refer to o or r or l or d you can refer to them by adding to a without changing a itself as they've done in the code. You could say that arrays are constant pointers, wherein their content can be changed, but whatever they point to when they are defined always remains the same. additionally, consider the following snippet (notice the placement of keyword const): CPP / C++ / C Code:
Last edited by machinated : 09-May-2004 at 08:02.
|
Recent GIDBlog
Writing a book by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Chaintech Geforce 5600 FX problems | bartster74 | Computer Hardware Forum | 8 | 04-May-2004 14:16 |
| Having problems displaying a line of variable length using winio. | warny_maelstrom | C Programming Language | 8 | 15-Feb-2004 12:56 |
| storing a token pointer as a string | CoreLEx | C Programming Language | 1 | 07-Oct-2003 12:33 |
| convert long to pointer to char | realpopeye | C++ Forum | 2 | 26-Sep-2003 11:22 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The