 |
|
Richelieu
|
|
Gatineau
Dec 2001 time: 00:24
|
|
OMFG! Pointers!!!! NOOOOOOOOOOOOOOOOOO!!!!
|
|
|  |
 |
|
Asher
|
 |
Calgary, Alberta
Nov 1999 time: 22:24
|
|
Here's how I'd declare a multi-dimensional array with dynamic allocation and pointers...
code: void allocateMatrix(int ***pMatrix, int size)
{
int i, j;
*pMatrix = (int **) calloc (size, sizeof(int));
**pMatrix = (int *) calloc (size * size, sizeof(int));
for (i = 0, j = 0; i < size; i++, j += size) /* init array indices */
{
*(*pMatrix + i) = (**pMatrix + j);
}
}
int main()
{
int **pMatrix;
allocateMatrix(&pMatrix,100);
return 0;
}
Last edited by Asher on 15-02-2005 at 00:29
|
|
|  |
 |
|
St Leo
|
 |
Member of the Apolyton Social Democratic Party
Jul 2005 time: 00:24
|
|
quote: Originally posted by Kuciwalker
I have an assignment to write a program that does a bunch of crap with matrices in C. One thing I have to do is randomize the contents of a matrix. I want to do this by copying random data from memory into the matrix (yes, I know there are other ways, but I'm not using them). So I have to create a pointer to an int[100][100] array, and then use malloc. I've tried declaring this as int temp[100][100]*, but the compiler gives me an error. I don't get an error if I declare it as int * temp[100][100], but I'm not sure if that's a point to a matrix or a matrix of pointers. Moreover, I have to cast malloc to a pointer to an int[100][100], but the compiler doesn't like temp = (int[100][100]*) malloc(40000), either. |
Dude, C arrays aren't objects or types. The array's name is a pointer to the zeroth element in the array. Square brackets are a convenience notation.
Zeroth of all, the following two lines are equivalent:
array[cell] = 1;
*(array + cell) = 1;
When you say array[cell], you are telling the compiler to follow the array pointer, advance cell sizeof()s beyond it, and do whatever.
First of all, the following to lines are equivalent:
array[row][col] = 1;
*(*(array+ row) + col) = 1;
That's right. Multi-dimensional arrays are just a hack job on top of the hack job.
The code that you want is probably:
int **p; // hi, I am a two-dimensional array
p = (int**)malloc(100 * 100 / sizeof(int)); // use me, baby
int ***a; // hi, I am the address of the two dimensional address
a = &p; // functions can now change the array by reference
void doStuff(int ***array, int row, int col) {
array[3][4] = 3;
}
doStuff(a, 100, 100);
// element at [3][4] is now 3
doStuff(&p, 100, 100);
// element at [3][4] is again 3
This is why I ****ing hate C.
|
|
|  |
All times are GMT. The time now is 05:24. Apolyton Time is 00:24. |
top of page
|
|
|
Forum Rules:
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is ON
vB code is ON
Smilies are ON
[IMG] code is ON
|
|
|
|
|
|