// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
char **p;
p = (char **)malloc(100);
p[0] = (char *)"Apple"; // or write *p, points to location of 'A'
p[1] = (char *)"Banana"; // or write *(p+1), points to location of 'B'
cout << *p << endl; //Prints the first pointer
}
In the above code :
p[0] = (char *)"Apple";
seems to reserve memory automatically. There is no malloc. Is this C/C++ standard or compiler specific?
UPDATE 1 I am actually interested how it is in C and then in C++. It is just that I did not have a C compiler installed for the code above, so I used C++.
So p is allocated on the STACK pointing to a block of memory (array) in the HEAP where each element points (is a pointer) to a literal in the DATA segment? Wow!
malloc
does dynamic memory allocation. Here you have classic static memory allocation, where string constants will be allocated in data section of your binary (if I'm not mistaken). Compiler knows in advance how many bytes you need, so it will just allocate it during compilation. This is as opposed to malloc, where you can ask for any number of bytes calculated in runtime and unknown in advance.
Same with arrays that you declare with constant length, without using malloc
.