-1

I was trying to find a way to allocate a single block of memory, but use multi-dimensional syntax, and I found the exact thing I was looking for on SO.

malloc in C, but use multi-dimensional array syntax

But after cut/pasting the code there:

  int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
    MAGICVAR[20][10] = 3; 

This error message pops up: "An array of type void * cannot be used to initialize an entity of type int(*)[200]" And it didn't help to cast the malloc to "int *" or "int **"

I'm using vs2010.

Community
  • 1
  • 1
PaeneInsula
  • 2,010
  • 3
  • 31
  • 57

1 Answers1

2

First, use a C compiler and not a C++ compiler to compile C code, second, if you have to use a C++ compiler, cast the return value of malloc to the declared type,

int (*MAGICVAR)[200] = (int(*)[200])malloc(400*sizeof *MAGICVAR);
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • +1, but really iff he has to use a C++ compiler, he should write C++ and not C. So it then would be `new int[400][200]` or something like this. – Jens Gustedt Sep 20 '12 at 11:22
  • Yes, must use C++ compiler. But using that cast "(int(*)[200])" was what I could not get. No idea why this question got down voted...but at least it got answered! Thank you. – PaeneInsula Sep 20 '12 at 15:21