0

I have an an integer array of values and I would like to make a double pointer to point to this array. I assume that this 1D integer array actually represents a 2D array. That is for instance that if I have an int A[2000*12] then I have 12 lines and 2000 rows. The problem is that I do not know how to initialize the pointer to point to the array A. My initial thought was like that:

  int A[2000*12];
  int **ptr;
  ptr=&A[0];

Of course this is not correct. More precisely I get the following error: incompatible pointer types in assignment

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Nick
  • 181
  • 2
  • 11
  • When you do `ptr=&A[0]` you are taking the address of the first element(`int *`). I don't know why you want double pointer to single dimensional array. – Nazar554 Nov 15 '13 at 14:47
  • I need this because this is a part of a bigger program. I actually try to run a program into a different processor architecture(VLIW). To do this i have to pass some arguments of a function through a given library function. Initially i had a double pointer. Then i passed all the data from the double pointer to a 1D array and now i have to get these data back to a double pointer – Nick Nov 15 '13 at 14:55

1 Answers1

0

Remove the [0] part:

int A[2000*12];
int **ptr;
ptr = &A;

EDIT: This however does not solve the problem with getting a 2D array. You still can't access it like

A[1][2] = 10;

because the compiler does not know the length of rows.

My favourite way of initializing a 2D array goes like:

int width = 10;
int height = 20;
int *_a = (int *) malloc(width * height * sizeof(int));
int **a = (int **) malloc(height * sizeof(int *));

The first allocation creates the 2D array, the second one creates an array pointing to each row.

int i, offset = 0;
for (i = 0; i < height; i++, offset += width)
{
    a[i] = _a + offset;
}

a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 2;
a[1][1] = 4;
// ...
Newerth
  • 449
  • 2
  • 12
  • Thanks for your answer. I will try to explain the problem again. Initially i had a double pointer which represents a double array of 2000 lines and 12 rows. Then i passed the data from this double pointer into a 1D array. So that in this 1D array i will have in the first 12 elements the first line , then for index=13 until 13+12 i will have the second line etc. Finally i want to find a way to extract these data from the 1D array back to a double pointer! – Nick Nov 15 '13 at 15:02
  • Edited the answer. Take a look at the for cycle. If I get your question right, this may solve your problem as it performs the expected conversion from a 1D to a 2D (double pointer) array. – Newerth Nov 15 '13 at 15:13
  • I'm glad I could help. Please mark the question as solved if you find it answered. – Newerth Nov 16 '13 at 09:15
  • How can i do that? Sorry This was actually my first post so I am kind of new here . – Nick Nov 16 '13 at 09:24