Paul brought this little gem to my attention. You'll need to be familiar with C to answer it. (He spent 2 hours fixing a bug which hinged on this issue.) So consider the following snippets of code:
int foo[256];
and
int *bar;
bar = malloc(256*sizeof(int));
foo and bar are functionally equivalent in most ways. You can use foo as a pointer, and you can use bar as an array. C doesn't even do array bounds checking.
One difference between the two is that the memory allocated for foo gets automatically released at the end of the function, whereas you'll have to manually free the memory used by bar.
But when you go about using them, there is another crucial difference. What is it?
Post your answer in the comments. I'll post it myself in a few days if no one gets the answer I have in mind by then. (For the record, when Paul asked me this, I gave him the first difference above, but I couldn't think of the second difference.)
Comments (3)
One difference is that you can make bar point somewhere else, but you can't change where foo points. (i.e. bar = foo is legal, but foo = bar is not.) I think this is caught by the compiler, so I don't see how it would cause a bug. I'll continue to think about it...
Posted by Matt | July 2, 2003
Posted on July 2, 2003
Yeah. Good point. But Paul's problem gave a runtime error.
Posted by ToastyKen | July 2, 2003
Posted on July 2, 2003
Okay, so the problem Paul had was that, although you can use foo in pointer arithmetic and bar in array references, they are conceptually different in memory. If you run sizeof(foo), you get 256*sizeof(int). But if you run sizeof(bar), you get sizeof(int*), which is probably just sizeof(int). Big difference!
Posted by ToastyKen | July 8, 2003
Posted on July 8, 2003