I'm writing a small C program to do some number crunching, and it needs to pass around arrays between functions. The functions should accept and return pointers, right?
For example, this (I know it may not be the most efficient thing):
int* reverse(int* l, int len) {
int* reversed = malloc(sizeof(*reversed)*len);
int i, j;
for (i = 0, j = len-1; i < len; i++, j--) {
reversed[j] = l[i];
}
return reversed;
}
Am I using pointers right?
In simple words, array names are converted to pointers. That's the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same. There are a few cases where array names don't decay to pointers.
An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.
An array is a pointer, and you can store that pointer into any pointer variable of the correct type. For example, int A[10]; int* p = A; p[0] = 0; makes variable p point to the first member of array A.
Your code snippet is correct. However, pointers and arrays in C are indeed different. Put simply "the pointer to type T" is not same as "the array of type T".
Please have a look at C Faq discussing Pointers & arrays to get a better understanding of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With