|
-
July 12th, 2006, 04:16 AM
#1
passing arrays to functions
Hi there.
Its me again!..and this time I have a silly question to put forward. it may sound silly but it has been troubling me from the inside.
I don't really understand why can i pass a one - dimensional (hereafter referred to as 1d) array to a function without ever passing the subscript and for any other dimensional array why do I need to still ignore the 1st subscript but pass the remaining ones.
for ex. if I have a 2d array say deck[4][13] and if I need to print the contents of the array,
then i just pass deck[ ][13] to the function.
Heres the sample function which does the printing:
Code:
void printArray(const int a[][ 13 ])
{
int i=0,j=0;
do
{
if(!j) printf("%4d",j++);//print a right justified 0 in a space of 4
else printf("%5d",j++);//print col. hdrs in a space of 5(rt. justified)
}
while (j<=12);
printf("\n\n");
for ( i = 0; i <= 3; i++ ) {
for ( j = 0; j <= 12; j++ ) //heres the actual printing taking place
printf( "%4d ", a[ i ][ j ] );
printf( "\n\n" );
}
}
How in the world will the compiler allocate memory space if it doesn't exactly know how many elements it needs to have?
Secondly what if I use a pointer to a constant data as the argument in the function header like const int *array instead of const int a[ ][13] and use pointer offset notation to print the elements?
Lastly (this is program specific), in the little code snippet above, I am trying to print the contents of the array. I am trying to have give column numbers above each column in the array. U can run and see it for urself because a pic(a sort of pic) speakes better than a thousand words so to speak. U can use the following code to initialize the array or u can initiaze it to 0 if u like.
Code:
for(row=0;row<=3;row++) //sequential initialization
for(col=0;col<=13;col++) //of every element to current
deck[row][col]=(col+1)+(row*13);//value of i.
What I do not understand is how does the program above works fine even if I remove the else clause! as per my understanding, it should mess up by printing a 0 over column number 0 and column number 1 both and the whole row which contains these column numbers should get displaced to the right by 4 spaces. But it doesn't! I may have overlooked something really obvious here but I can't figure that out. pretty silly u'll say..ya it is..
Hoping to hear from you soon,
Best Regards,
Aijaz Baig.
Last edited by aijazbaig1; July 12th, 2006 at 04:22 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|