What's the difference between an array and a pointer in C exactly?
This question may sound stupid but I'm not really sure about it. I mean, what's the difference between:
char* line = (char*) malloc(MAX_LINE_LEN);
and
char line[MAX_LINE_LEN];
exactly? I know the former is a pointer and the latter is an array, but how can the system tell the difference? How is the memory allocated/stored?
Also, why can you delete the memory occupied by line
when it's declared as a pointer, but not when it's an array? I think that an array is stored somewhere else and the system automatically deallocates its memory when it's out of scope, which doesn't happen when you are dealing with a pointer so you must delete it yourself. Am I wrong?
char* line = (char*) malloc(MAX_LINE_LEN);
This is poor style; You don't need to cast malloc
in C. Let's break this up into two sections, because it's easier to describe and compare that way:
char *line;
declares a pointer to char named line
. You can assign it to point to an object (or nothing). The sizeof
an object is the size of it's type, so sizeof (line)
is sizeof (char *)
, which varies from system to system. &line
is the address of a char *
, which has the type char **
(pointer to pointer to char). It's storage duration depends upon where it is declared:
If it's declared outside of any function, it has static storage duration, which lasts for the lifetime of the program. Objects with static storage duration are initialised to 0
, unless an explicit initialisation exists (eg in your case). 0
is a null pointer constant
, indicating that this object would point to nothing if it were declared outside of functions without an initialiser.
If it's declared inside of a block of code, it has automatic storage duration, which lasts until execution reaches the end of that block of code. Objects with automatic storage duration must be explicitly initialised or assigned to before they're used, because their value otherwise is indeterminate.
Your initialisation assigns a value to it, so it won't start off indeterminate regardless. malloc
returns a pointer to an object that has dynamic storage duration, which means the object that the pointer points to persists until it is explicitly free
d.
Think of this line
like the postcode on a mail envelope; You can write something in there, and that something will indicate a location where you can find objects (and people). The postcode doesn't tell you anything about the size of the objects (or people).
char line[MAX_LINE_LEN];
This declares an array of MAX_LINE_LEN
chars.
If declared outside of any functions, it has static storage duration and the entire array is zero-filled.
If declared inside a function or block of code, it has automatic storage duration and the values in the array are indeterminate; They need to be initialised (eg char line[MAX_LINE_SIZE] = { 0 };
will initialise all of them) or assigned to (eg line[0] = '