I want to create a double pointer and make it point to an double dimension array, then output the content of the array through the pointer. However Gcc warn me that "assignment from incompatible pointer type". Just like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i,j;
	int **p;
	// First one.    this doesn't work, why?
	int a[2][3]={{1,2,3},{1,2,3}};
	for(i=0;i<2;i++)
		p[i]=a[i];
	p=a;
	for(i=0;i<2;i++)
		for(j=0;j<3;j++)
			printf("p[%d][%d]=%d\n",i,j,a[i][j]);

	// Second one.    this one works.
	int **b=(int **)malloc(2*sizeof(int *));
	for(i=0;i<2;i++)
		b[i]=(int *)malloc(3*sizeof(int));

	for(i=0;i<2;i++)
		for(j=0;j<3;j++)
			b[i][j]=j+1;
	p=b;
	for(i=0;i<2;i++)
		for(j=0;j<3;j++)
			printf("p[%d][%d]=%d\n",i,j,a[i][j]);

	return 0;
}

Please could anyone tell me why the first one doesn't work while the second one does work?
Thanks to any suggestions.

The first one doesn't assign or allocate any memory for the pointer to point to.

Doesn't "int a[2][3]={{1,2,3},{1,2,3}};" allocate memory for "a"? I think there's memory for 2D arrayy a, and "a" can be seen as a double pointer. Then "p=a;" let pointer p point to the memory allocated for 2D array a. Is that wrong? Thank you for your suggestion.

The first one doesn't assign or allocate any memory for the pointer to point to.

Thank you very much. Now I know where's the problem. I don't allocate memory for p. In C language, "int a[3][3];" will allocate 13 bytes when sizeof(int) equals 4. And the compiler will allocate 4 extra bytes by default. Is that right?

For a pointer to be valid you must assign it memory to point to, like below

int x = 1234;
int *iptr = &x;
/*Now iptr points to x*/

or, you must allocate it memory with malloc...like below

int *iptr = (int*)malloc(1 * sizeof(int));
/*Now iptr points to the memory allocated on the heap*/

Edited 6 Years Ago by gerard4143: n/a

This article has been dead for over six months. Start a new discussion instead.