I was just curious - why does C allow you to pass dereferenced pointers when a function is expecting a pointer. Here's an example:
typedef struct {
char message[255];
} Bla;
// so he's the function that's expecting the pointer
void cool_function(Bla *_bla) {
}
Bla *woot = (Bla *)malloc(2 * sizeof(Bla));
woot[0] = (Bla) {
.message = "bla bla bla"
};
// woot itself is a pointer, but it's getting dereferenced when I am adding [0]
cool_function(woot[0]);
Now that compiles fine, but when I go to actually use _bla (ie. _bla->what), BAM, runtime error.
So this confuses me -- what happens to it if it's passed by value to this function that is clearly expecting a pointer? Why does it even compile?
I'm fairly new to C, so please don't jump all over me. :/
* UPDATE *
Sorry for not mentioning earlier, but this is an app for the Pebble Watch, which is using a special version of gcc for specific arm processors (arm-cs-tools).
* UPDATE 2 *
I think I found out why it was doing that. The function 'cool_function' was actually in a separate file, and when I declared the function in the header, it was only declared with void cool_function()
- forgot to include Bla *_bla
. But the definition was void cool_function(Bla *_bla)
. It was all my fault for confusing the compiler.
You should get the compiler error:
error: passing 'Bla' to parameter of incompatible type 'Bla *'; take the address with &
cool_function(woot[0]);
If you use gcc or clang, try to compile your program with -WError and -Wall options.