POINTERS AND ARRAY'S IN C

I recently saw this in a blog post and I see stuff like it all the time and nobody speaks up "`int x[1000]` in C or C++ doesn't have much meaning. It's semantically equivalent to declaring "x" as `int *x`. You can reassign X any time you want, to make it point to a different location." This is a really bad example but even some text books get it wrong so I'll explain it. You can never assign to x because x is off type array of t(array of int) The c, c++, c99 standards do not allow it.

int x[1000] allocates the memory for 1000 Int's.

int * x allocates the memory for a pointer to int."

//try this code

int x[1000];

int * y = x; //this is just a pointer to x so what

x = y; //you'll get a error here cant assign * int to int[1000]

or something like that of the top of my head.

Pointers and arrays are not the same in c they just can share the same syntax in some situations for example

int x[1000]; int * y = x;

int test = x[5];

int test = y[5];

//these return the same value in this situation

//or you could do something like this

int test = *(y + 5)

and there are a number of other ways to do the exact same thing. the important thing to remember is just because the syntax is the same the operation is not the same. Reconsider the example above.

int test = x[5]; //x is array of int

int test = y[5]; //y is pointer to int

In this case x is type array of t(array of int) y is type pointer to t(pointer to int) Just because the compiler converts array of t to pointer to t and happens to give the same result. It does not mean that pointer to t is the same as array of t by any means. Arrays just happen to decay into pointers in function calls so many newbies assume them to be the same. Try switching them in a extern and see how equivelent they are. The standard will not allow you to alter the value of the address of x only take it. So there are really two main differences you can not assign a new value to array of t. But you can assign one to pointer to t, Also array of t allocates storage for a array where as pointer to t allocates storage for a single pointer in the example above. Sorry if this seems complicated but this is the simplist way I can explain it.

Read deep C secrets, this is a great book for anybody who needs to use pointers. It covers a lot of stuff most other book don't even touch upon or gloss over.

More Programming Tutorials