Click to See Complete Forum and Search --> : Pointer to array


am_abbas
May 6th, 2003, 07:09 AM
Hi,

In the below program, while compiling I getting a warning
" warning C4047: '=' : 'int (*)[10]' differs in levels of indirection from 'int *' ". But it works as expected. Also I dont want to change the declaration "pointer to array". How can I eliminate this? Please any one help.

#include <stdio.h>
main()
{
int (*n)[10];
int i,ii;

n=(int *)malloc(sizeof(int)*1024);

for(i=0;i<10;i++)
{
for(ii=0;ii<10;ii++)
{
n[i][ii]=ii+i;
}
}

for(i=0;i<10;i++)
{
for(ii=0;ii<10;ii++)
{
printf("%d\n",n[i][ii]);
}
}

}

mwilliamson
May 6th, 2003, 09:16 AM
An array is a pointer, there is no need for a declaration like yours. And why do you multiply sizeof int by 1024? If you want an array of ints, do this:


intmain()
{
int* array = NULL;
array = (int*)malloc( sizeof(int)*10 ); // 10 elements of an array
}

if you want a 2 dimensional array, do this:

int main()
{
int** array;
array = (int**)malloc( sizeof(int*) * 10 ); // 10 in pointers

for( int i = 0;i < 10;i++ )
array[i] = (int*)malloc( sizeof(int) * 10 ); // 10 ints
}

Andreas Masur
May 6th, 2003, 09:29 AM
Is there any reason why you cannot use the standard vector template class? It is much easier than the old ANSI C arrays and it provides its own memory management.

For an introduction to the vector class take a look at this article (http://www.codeguru.com/cpp_mfc/vector.html)...

Also...for the usage of vectors as two-dimensional arrays take a look at this FAQ (http://www.codeguru.com/forum/showthread.php?s=&threadid=231046)...

Elrond
May 6th, 2003, 10:09 AM
The fact is that your declaration: int (*n)[10]; is that of a two dimensional array. At the same time, your memory reservation is that of a one dimensional array: (int*).

That is the cause of your problem.

Why kind of array are you exactly trying to do?

two dimensional: 10*N or N*10 ?

Or is it something else.

am_abbas
May 6th, 2003, 10:50 AM
I am trying to have a N*10 array. Thanks for your interst.

Thanks and Regards,
Abbas

Elrond
May 6th, 2003, 11:51 AM
Using new is usually better than malloc when coding in C++. Or are you coding in C?

This works anyway:

int (*n)[10];
UINT N = 7;
n = new int[N][10];

for (int i = 0; i < N; i++)
{
for (int j = 0; j < 10; j++)
{
n[i][j] = i*j;
cout << n[i][j] << " ";
}
cout << endl;
}

delete [] n;

am_abbas
May 7th, 2003, 12:21 AM
I am working with C. I am stuck with C because I work in a API development of a CAD package which only supports C. Thanks you very much!

Thanks and Regards,
Abbas