OK. Pointers for the Java guy.
When you declare
int *a;
it is the same as in Java doing:
Integer a;
Java does not have pointers, but all objects are held by references. So,
Integer a = new Integer(3);
is the same as:
int *a = malloc(sizeof(int));
in C.
Now, Java does not have an & operator, and you cannot do pointer arithmetic, but references really are roughly the same otherwise.
To answer your questions:
- does it always have to come from the heap?
No. In C you can point a pointer at something that is already allocated on the stack (or anywhere else in RAM, such as a DMA register for doing hardware interactions):
void f() {
int i;
int *a = &i;
*a = 3; // same as i = 3
a = (int*)0x12340000; // some address in memory, possibly screen RAM?
*a = 0xffffffff; // possibly set some colors on the screen
}
- Do I have to use malloc and sizeof every time to allocate space?
If you do use malloc, then yes, you have to specify how much space you want. But you can just as easily ask the compiler to allocate the space in static data space:
void f() {
char *p = "hello";
....
}
In this case, the literal string typically becomes part of the compiled program, and is placed in a statically allocated spot at program startup by the OS.