What does (int (*)[])var1 stand for?
Asked Answered
S

3

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!

Sumbawa answered 4/6, 2010 at 9:45 Comment(0)
M
11

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

Melesa answered 4/6, 2010 at 9:50 Comment(3)
I was going to suggest the cdecl tool, nice to see a web front-end for it :)Hesler
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?Bullfrog
@R.. according to comp.lang.c faq: "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.Comical
C
1

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

Catamaran answered 4/6, 2010 at 9:52 Comment(0)
E
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.

Errecart answered 4/6, 2010 at 9:51 Comment(3)
I think you should rephrase your answer, because int[][] is not valid C syntax and it remains unclear what you mean.Dewayne
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).Dewayne
@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.Errecart

© 2022 - 2024 — McMap. All rights reserved.