In an effort to stop being such a fucking noob, I’ve seriously taken up C. As a natural transition/crutch, I have started with PHP extensions. The PHP API basically picks your droppings up after you with a plastic bag, so it’s pretty easy. Using ext_skel gave me pretty much everything I needed, since I’ve only written one function so far and have not done anything fancy.
The extension is called “human,” short for “human readable.” The first function, human_interval_precise, simply represents a number of seconds in the largest “precise” time units possible. That is, thousands of seconds are converted to weeks, days, hours, minutes, and seconds as needed. The source is here.
Lessons
I’m obviously still a giant noob, but there are some things that I have picked up along the way (mostly via Crowley) that made things a lot clearer. Hopefully my posting this will help other noobs following in my footsteps.
“Pointers are just numbers”
Yup. Just the number of memory blocks from the start of the segment of memory you’re dealing with. “Pointer math” is really just math: p+5 really is just the position in memory 5 blocks away from the start of p. The size of the blocks is determined by the pointer type, so if you have a char pointer, the blocks are 1 byte.
an array is just a pointer to a set of consecutive memory blocks
The name of the array is just the pointer to the first element. This is particularly important with char arrays. When I do the following in my code, I am just adding output to the end of an already existing “string.”
sprintf(retstr+strlen(retstr), "%dd ", days);
The K&R section on the relationship between arrays and pointers is incredibly useful.
Always remember to initialize your strings
Nothing says “FAIL” like running your PHP function more than once in the same script and seeing it return its result appended to the end of the result from the previous call. A simple
*retstr = 0;
at the top of the function takes care of the problem. Otherwise, your char pointer ends up pointing to memory that isn’t claimed by anything else, but isn’t cleared either. In the case of consecutive PHP function runs, it just happens to be the previous output. It could end up being any sort of useless garbage.
I started writing this entry a few weeks ago and got sidetracked by a bigger and more interesting project/thanksgiving. As a result, I don’t remember what else I was going to write, so I’ll just wrap it up. More C learnings coming soon. It has been a humbling experience to say the least.