I am trying to figure out the insides of a double pointer (which is a pointer holding another pointer) in order to form an array of pointers. So, I am trying to run the following code, experimenting with malloc for debugging and seeing how it works. I can't figure out what malloc(0) does in my case, but my code works by outputting "Hello World".
What's the difference between
pToCharsPointers = (char**) malloc(0);
and
pToCharsPointers = (char**) malloc(2 * sizeof(char*));
Please check what he does in my case.
#include <stdio.h> char **pToCharsPointers; int main(void) { pToCharsPointers = (char**) malloc(0); char* pToChars = "Hello"; *pToCharsPointers = pToChars; *(pToCharsPointers + 1)= "World"; printf("%s %s\n", *(pToCharsPointers + 0), *(pToCharsPointers + 1)); return 0; }
Also, I would really appreciate it if you could explain how double pointers work with an example in memory for visualization, since I don't see myself, although I tried to read about it in many places.
EDIT: Thanks to everyone for sharing your answers, and it really helped to understand. I got a valid pointer with malloc (0) when I printed it, and can dereference it also without problems during several attempts. I wanted to understand why it works. It looks like in my case the undefined behavior was actually expected.
source share