-8

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]?

MD XF
  • 7,860
  • 7
  • 40
  • 71
cxsp
  • 1
  • 5
    Yes. Please, next time, try before asking.... – Michel Billaud Jun 26 '15 at 15:38
  • All that is "*declare*"d in the code you show is a pointer to `int`, namely `m`. – alk Jun 26 '15 at 15:41
  • @MichelBillaud: Where? – alk Jun 26 '15 at 15:43
  • Has been fixed in the mean time you posted. Comment deleted. – Michel Billaud Jun 26 '15 at 15:47
  • Yes, its possible. However this only works for on-diminsional matrices (arrays). For two dimensional matrices its trickier – hugomg Jun 26 '15 at 15:54
  • 2
    @MichelBillaud: Please be careful with this advice. "Try it and see" is responsible for all too many false lessons. For example, if you want to know what `i = i++` does, "try it and see" is just about guaranteed to give you the **wrong** answer. In Carmine's case, we might say "Please, next time, read any basic introduction to pointers before asking." – Steve Summit Jun 26 '15 at 16:22
  • @SteveSummit I am! And the question here is specifically about syntax. Not undefined behaviours. – Michel Billaud Jun 26 '15 at 16:34

2 Answers2

2

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.

MD XF
  • 7,860
  • 7
  • 40
  • 71
johnny838
  • 922
  • 7
  • 15
1

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198