x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 3665

# 2d array-pointer

double **p;

.. ... .

... . ..

p= (double *) malloc(sizeof(double) * ( m*n)) ;
... ..

for ( i .... .. .
for ( j ......

*(*(p+i)+j)++;
}
}

it is not working because of molloc operation. i try to do, sorted numbers which lenght is m*n... like array[m][n]..
0
thefirstfbli
3 Solutions

Data Warehouse Architect / DBACommented:
Hi thefirstfbli,

You don't need to do a double dereference here.  The structure that you're trying to create is a table of doubles, NOT a table of pointers to doubles.

Just define the structure as "double *p" and don't get caught up in the double dereferencing.

Good Luck,
Kent
0

Author Commented:
ok but

for ( i=0;i<n;i++)
for(j=0;i<m;j++)
{
but in this line ;

*(*(p+i)+j)++;
}

it gives error..

i did this like

arr[100][100];

for ( i
for ( j
a[i][j]=inc;
inc++;

but it is not dynamic..  because i dont know the n and m values .. it comes from somewhere..
0

Author Commented:
" invalid type argument of unary * "  is the fault for the line *(*(p+i)+j);

above, there is no ++ after it..
0

Commented:
p= (double **) malloc(sizeof(double*) * n) ;
for( i=0;i<n;i++ ){
*(p+i) = (double *)malloc( sizeof(double)*m);
}
for ( i=0;i<n;i++ ){
for( j=0;j<m;j++ ){
(*(*(p+i)+j))++;
}
}
0

Commented:
Shouldn't it be
*(*(p+sizeof(double)*i)+sizeof(double)*j)++;
0

Commented:
>Shouldn't it be
>*(*(p+sizeof(double)*i)+sizeof(double)*j)++;

Pointers are set up such that (p+1) will always point to the next element after (p). "p++" or "p+1" will increase the pointer's value by the sizeof the element it's pointing to.
0

Commented:

.malloc is fine it will allocate required memory
.problem was the statement
*(*(p+i)+j)++;
here you are assuming that (p+i) will point to next row of the array which is incorrect.
Here p is **double.

To solve the problem you should declare p correctly this piece of code will solve your problem.

double (*p)[N];//pointer to array of N double data type

p = (double (*)[N]) malloc(sizeof(double)*M*N);//type cast malloc correctly.

0

Commented:
If you're doing one malloc, you're allocating one array.  So, all references have to be in the same array.

If you say double*p = malloc(sizeof(double)*M*N), then you have to refer to elements like p[i*N + j], assuming M is height, N is width,  i is the row and j is the column.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.