Sunday, September 12, 2010

Woof, pointers

My first attempt at learning C in high school ended when I couldn't understand pointers. I figured it was too important to just truck on without understanding them, so I stopped. This time around I have more discipline and focus (I hope), so I'm making sure that I keep throwing myself against the wall until I start making a dent, or at least a worn out area.

I'm writing little programs to poke around at the behavior of pointers. I might be hosing myself early on since I'm using printf() to print out the results of my little tests, and printf() might be smart enough to do things right even if I'm not. For example:

char sometext[] = "THIS IS SOMETEXT";
char *someothertext = "THIS IS SOMEOTHERTEXT"

sometext is a character array, and someothertext holds a memory address to a space in memory where "THIS IS SOMEOTHERTEXT" starts.

My book here says that (with my variable names substituted) "Since the name of an array is a synonym for the location of the initial element, the assignment someothertext=&sometext[0] can also be written as someothertext=sometext".

Ok, I can buy that, but where things get confusing for me is when you try to go the other way.

I can't say:

sometext = someothertext

...without my compiler barking at me with "error: incompatible types with assigning to type 'char[17]' from type 'char *'".

Ok... but why? You just said that sometext (just the name) holds the address of where a string starts. I want that address to now be the same address that someothertext holds. It very well might be that the compiler is trying to save me from myself, OR this might be one of those "core concepts behind programming" that I haven't internalized yet or have been exposed to in my self-taught journey.

In my fiddling around, I also tried to trick it and say:

&sometext = someothertext

...just to see if that would make it work, but no go.

Stuff like this irks me because I'm afraid I'll be forced to move on without really understanding it, and then it will bite me in the ass down the line.

No comments:

Post a Comment