Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are pointers and arrays any different in C?

Tags:

arrays

c

pointers

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?

like image 408
Javier Avatar asked Jun 28 '09 04:06

Javier


People also ask

Are pointers and arrays same in C?

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.

What are the differences between pointers and arrays?

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.

Is there any relation between array and pointer?

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.

Is an array just a pointer?

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.


1 Answers

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.

like image 134
Aditya Sehgal Avatar answered Sep 22 '22 13:09

Aditya Sehgal