Is it possible to use notation [] with pointers in C?

112 views Asked by At

I declare a matrix of integer using malloc():

int *m;
m = malloc(10 * sizeof(int));

Can I use array notation [] to select an element from matrix?

For example: I use *(m+1) to select the second element of matrix m. Can I select the second element of matrix m through this notation: m[1]?

2

There are 2 answers

0
johnny838 On

Yes this is possible. However, if you are specifying it as a static size, you may as well do int m[10] in your declaration.

0
John Bode On

a[i] is defined as *(a+i), so yes, the [] subscript operator works with array and pointer expressions.

Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initilialize another array in a declaration, an expression of type "N-element array of T" is converted ("decays") to an expression of type "pointer to T", and the value of the expression is the address of the first element of the array.

So, for an array a, if you write a[i], the expression a is converted from an array type to a pointer type, and the [] operator is applied to the resulting pointer expression. For a pointer p, no conversion is necessary, and the [] operator is applied to p directly.