-1

I understand this question has been asked before, but I can't quite narrow down what i've done wrong here

int* arr[2];
arr = (int (*)[2]) malloc(sizeof(int) * size);

why is visual studio telling me the expression must be a modifiable lvalue? I'm trying to create an array with a constant column size, since that will always be two, but the rows will vary.

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • Many problems here. `arr` is an array, not a pointer. The cast type `(int (*)[2])` doesn't match the target type. The size argument to `malloc` seems to be wrong (but can't know for certain until it can be compared to a valid pointer declaration). – Tom Karzes Feb 02 '16 at 22:39
  • Do not cast the result of `malloc` & friends in C! – too honest for this site Feb 02 '16 at 22:39
  • Arrays cannot be assigned to as a whole in C . You can only assign to elements of the array. – M.M Feb 02 '16 at 22:41

3 Answers3

2

arr is an array of pointers. You cannot assign anything to it once it is initialized. Since you are trying to set its value to be the return value of a call to malloc, you probably want it be a pointer to an array. In that case, use:

int (*arr)[2];

Also, don't cast the return value of malloc. See Do I cast the result of malloc?.

Use

int (*arr)[2];
arr = malloc(sizeof(*arr) * size);
          // ^^^^^^^^^^^^ We are speculating this is what you need,
          //              not sizeof(int)

If you want arr to point to an array of 15 x 2 objects, you will need to use:

arr = malloc(sizeof(*arr) * 15);
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Shouldn't there be a `*2` in the `malloc`? If not, why not? – Barmar Feb 02 '16 at 22:40
  • Your malloc size is wrong. Suggest `malloc(size * sizeof(*arr))` – M.M Feb 02 '16 at 22:41
  • Can I ask how you would access elements of that? It seems like the OP wants each element to be length two arrays, eg. `int* a = arr[0];` Or is there a way to get it as an array? – matt Feb 02 '16 at 22:51
  • @matt, Sure, they can do that. Since `arr[0]` is of type `int [2]` and decays to the pointer to the first element in the array, it's OK to use `int* a = arr[0];`. – R Sahu Feb 02 '16 at 22:59
0

you have an array of pointers.... that array can't be used as a pointer itself, only the array entries are pointers.

you need a pointer to pointers, int **, unless you are wanting an array of ints, then you just int* arr

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

Did you consider using a struct? Then the syntax is a little more straight forward.

#include <stdlib.h>
typedef struct Two Two;
struct Two{
  int b[2];
};
int main(){
  int size = 100;
  Two* two = malloc(sizeof(Two)*size);
  return 0;
}
matt
  • 10,892
  • 3
  • 22
  • 34