Need some help with explanation c++

Define a void function that will assign every element in an integer 2d array to 0. How does the function call and function prototype differ between statically versus dynamically allocated arrays?
That looks like you've just copied and posted an entire homework question. We're not a free homework answering service.

Can you please clarify exactly what aspect of it you're having trouble with, and show us what you've done so far?
hint: if you do it right, the prototype should be identical for both. The *name* of an array *is* a pointer, in terms of syntax and in many of the uses (obviously can't new/delete it).
jonnin have you tried what you said? I'm pretty sure the difference is needed. Last time I tried doing that, you can't pass a static 2D array as just type** array_param.
Ex, this should not compile, the compiler needs to know that it is a pointer to int[10]:
1
2
3
4
5
void foo(int** barr) { }
int main() {
    int bar[10][10];
    foo(bar);
}
Last edited on
Correct. But you can hack into it with a single int * and knowledge of how the memory is aligned. Its ugly, but I don't know of another way due to the limitations of the language syntax.

you can make a function, pass it bar[0] reshaped as an int*, and access that [23] or whatever location...

you must know its dimensions and how to convert from 1d back to 2d etc, but it does work. This may be one of those 'undefined but works on all compilers' things.

... a hideous example of this sort of mess (this is why vectors and single dimensional pointers are preferable ...)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void foo( int *x)
{
   x[23] = 1000000;
}

int main()
{
   int z[10][10];
   int i,j;
   for(i = 0; i < 10; i++)
   for(j = 0; j < 10; j++)
     z[i][j] = 1*10+j;
	

foo(z[0]);	
	 
	 for(i = 0; i < 10; i++)
   for(j = 0; j < 10; j++)
   cout << z[i][j] << endl;
   
   
  return 0;
}


I would not actually do this, but then again, I would not actually use a 2-d array either.

I think you can also abuse the cast syntax to force the single pointer back to a double * and index into it normally if you really want to.

Of course this is left over from dealing with C. C++ it may be best to just overload the function headers ... regardless, its a miss on the language syntax since it isnt necessary to feed it the hard coded sizes, nor should it be.

Last edited on
Hah yeah what a mess. I wouldn't actually use 2-d arrays either.
Topic archived. No new replies allowed.