I can be a C-numptie

This might not be earth-shatteringly new to those who have seen my code before, but I was a little surprised. 🙂

A C program that I wrote a little while ago (and has previously worked fine on Windows, Linux, Solaris and HP) failed horribly on AIX. A little digging showed that I had written:

char* thisIsSupposedToBeAString[256];

I guess that at the time I wrote it (presumably early in the morning, and caffeine-fuelled) I had a string (char thisIsSupposedToBeAString[256];) and wanted a pointer to it, so went back and stuck a * on it without thinking.

The problem is that strings in C are icky. You don’t really have a string object – your char variable is a pointer to the start of the string, and the string functions just keep going until they hit something that tells them they’ve reached the end. So thisIsSupposedToBeAString was already a pointer, before I went and messed about with it. In fact, by sticking a * on it I created a pointer to a pointer.

Instead of having a pointer to a 256-character string like I guess I thought I had, I’ve ended up with an array of 256 strings… or, an array of 256 pointers to pointers to a character. Or something like that. Erg…. sometimes I really don’t like C 🙂

In fact, while I am admitting to supreme uselessness, I guess in an attempt to get the compiler to stop complaining about my gibberish code, I used this:

char* thisIsSupposedToBeAString[256];

to pass the string to another function. So, in my attempt to pass a pointer to my string, I was casting an address-of-a-pointer-to-a-pointer-to-a-char, to a pointer-to-a-char. Clever(!) And AIX is strict enough that it doesn’t like it. Although now I look at it, I’m amazed the other platforms all let me get away with it…

And for those who are now thoroughly lost, the code now looks like:

char thisIsActuallyAString[256];

Maybe I should stick to high-level languages? 🙂

Comments are closed.