stdcerr
stdcerr

Reputation: 15598

copy 1d element 2d array

I have a 2d array and need to copy one 1d element into a single array. I tried to duplicate my issue in below example. But below example doesn't even compile, gcc complains

subscripted value is neither array nor pointer`

at line TwoDArray[9][99] = 99;, why is that? I don't quite understand, any help would be appreciated!

int main(void)
{
  int i = 0;
  int* TwoDArray;
  int DestArr[100] = {0};

  TwoDArray = calloc(10,sizeof(int*));
  for (i = 0; i < 10; i++)
    TwoDArray[i] = calloc(100,sizeof(int));

  TwoDArray[9][99] = 99;

  memcpy(DestArr, &TwoDArray[9],sizeof(int)*100);
  printf("DestArr[99] %d\n",DestArr[99]);


return 0;
}

EDIT1:

I mistakenly didn't declare int** TwoDArray as pointer to pointer - after changing this, it now compiles flawlessly but the value in my result is 0 and I'd expect it to be 99 - why is this?

Upvotes: 1

Views: 75

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your code, TwoDArray is a pointer, pointer to an int.

So, the memory allocation should look like

 TwoDArray = calloc(10,sizeof(*TwoDArray));  //i.e., sizeof(int)

instead of

TwoDArray = calloc(10,sizeof(int*));

and TwoDArray[i] being of type int, does not need any malloc-ation, whatsoever.

So, you can use TwoDArray[i], provided i is within bounds.

TwoDArray[9][99] is invalid, as TwoDArray[9] is not a pointer, anyway.

Related, to use the array subscript operator,

postfix-expression [ expression ]

One of the expressions shall have type ‘‘pointer to complete object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.

In case of TwoDArray[9][99], TwoDArray[9] is certainly not a pointer to complete object type.


Edit:

In case you use

 int** TwoDArray;

and

 TwoDArray[i] = calloc(100,sizeof(int));

then, you need to change

memcpy(DestArr, &TwoDArray[9],sizeof(int)*100);

to

memcpy(DestArr, TwoDArray[9],sizeof(int)*100);
              ^^

as TwoDArray[9] itself is now the pointer you're interested in, not the address of the pointer.

Upvotes: 1

Related Questions