8

I found this example code and I tried to google what (int (*)[])var1 could stand for, but I got no usefull results.

#include <unistd.h>
#include <stdlib.h>

int i(int n,int m,int var1[n][m]) {
    return var1[0][0];
}

int example() {
    int *var1 = malloc(100);
    return i(10,10,(int (*)[])var1);
} 

Normally I work with VLAs in C99 so I am used to:

#include <unistd.h>
#include <stdlib.h>

int i(int n,int m,int var1[n][m]) {
    return var1[0][0];
}

int example() {
    int var1[10][10];
    return i(10,10,var1);
} 

Thanks!

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Framester
  • 33,341
  • 51
  • 130
  • 192

3 Answers3

11

It means "cast var1 into pointer to array of int".

Michael Madsen
  • 54,231
  • 8
  • 72
  • 83
  • I was going to suggest the `cdecl` tool, nice to see a web front-end for it :) – crazyscot Jun 04 '10 at 12:29
  • 1
    I'm confused - there's no such type as "array of int". Array types must have a size, even if it's variable. Is this type used in the cast really valid? If so, what does it mean? What is `sizeof *(int (*)[])0`? – R.. GitHub STOP HELPING ICE Nov 11 '10 at 04:18
  • @R.. according to [comp.lang.c faq](http://c-faq.com/aryptr/ptrtoarray.html): "If the size of the array is unknown, N can in principle be omitted, but the resulting type, 'pointer to array of unknown size,' is useless." And behavior is an incomplete type error on gcc. – Michael Lowman Aug 03 '11 at 22:04
1

It's a typecast to a pointer that points to an array of int.

Curd
  • 12,169
  • 3
  • 35
  • 49
0

(int (*)[]) is a pointer to an array of ints. Equivalent to the int[n][m] function argument.

This is a common idiom in C: first do a malloc to reserve memory, then cast it to the desired type.

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • I think you should rephrase your answer, because `int[][]` is not valid C syntax and it remains unclear what you mean. – Jens May 20 '11 at 21:17
  • And why would you cast the return from malloc? It's a pointer-to-void, which can be assigned to any pointer type without a cast in C. (In C++ you don't use malloc in the first place, but `new`). – Jens May 21 '11 at 08:12
  • @Jens: I should have just shut up :) I'm no C guru, so I could only interprete what the code meant, not see what it should have read. – xtofl May 21 '11 at 09:02