Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of pointers to arrays?

Tags:

arrays

c

pointers

So, I was reading about pointers, and came across the concept of pointers to arrays. The thing is that a pointer to an array doesn't really seem useful at all, since instead of using a pointer to have an offset to access an array element, I could just get the element directly. However I feel as if I'm missing the reason why these can be useful.

So, in short, What is the point of pointers to arrays; How and why should they be used, and do they have any practical applications?

Edit: I meant this in the context of normal/simple arrays such as:

int array[5];

Edit: As Keith Pointed out, I'm specifically asking about pointers to arrays, for example char (*ptr)[42] which is a pointer to a 42-element array of char.

like image 905
Rivasa Avatar asked Oct 05 '13 16:10

Rivasa


2 Answers

Unfortunately some answers you received show misbeliefs about pointers and arrays in C, in brief:

1) Pointer to array is not the same as pointer to first element.

2) Declaring array type is not the same as declaring pointer.

You can found full description in C faq part related to common confusion between pointers and arrays: http://c-faq.com/aryptr/index.html

Adressing your question - pointer to array is usefull to pass an entire array of compile-time known size and preserve information about its size during argument passing. It is also usefull when dealing with multi dimensional arrays when you what to operate on subarray of some array.

like image 55
mfxm Avatar answered Oct 24 '22 22:10

mfxm


In most expressions, an object of type "array of T" will degrade to the address of the first array element, which will have the type "pointer to T". In this sense, a pointer type can be used to represent an array of items, and is used to do so when there is need to dynamically allocate an array.

// ptr used to dynamically allocate array [n] of T
T *ptr = malloc(n * sizeof(*ptr));

In the case of a pointer to an array, then, it can be used to represent an array of arrays, and/or dynamically allocate an array of arrays. So, a pointer to an array can be used to represent a 2-dimensional array.

// ptr used to dynamically allocate 2 dimensional array [n][10] of T
T (*ptr)[10] = malloc(n * sizeof(*ptr));
like image 38
jxh Avatar answered Oct 24 '22 22:10

jxh