Friday, May 21, 2010

Quick question about Arrays?

When an array parameter is passed to a function





a. the elements of the actual array parameter are copied into the elements of the formal array parameter.





b. the elements of the formal array parameter are copied into the elements of the actual array parameter.





c. the formal parameter is a pointer that holds the address of the actual array parameter.





d. the programmer must write code which allocates enough space for the function to store the array.





I got this wrong on a Comp Sci exam and I'm just wondering what the answer is

Quick question about Arrays?
Actually, the answer is language dependent. But it's not d, as I'm not aware of any language that behaves in such a manner.





I'll assume you refer to the C model for arrays. Take a look at http://c-faq.com/aryptr/aryptrparam.html





So the answer would be C. Pointer-array equivalence is a tricky topic, and I recommend you spend some time on the C FAQ site, reading the answers.





EDIT:





You've got conflicting answers, with some claiming the answer is a and some c. Again, the answer is language dependent.





However, in C or C++, there is no question. When passing an array, it's almost like a pass by reference. Or you can think of it equivalently as passing a pointer. There is no copying involved. Yes, the everything else has a pass by value. That is not true for C.





If you don't believe me, you can test it out for yourself. Pass an array to a function, and modify the array in the function. The original values should have changed.





NOTE:


This is a tricky question. The equivalence of pointers and arrays is a bit confusing. It helps to have sites like C FAQ, usenet references, cprogramming.com, gamedev.net, and other places where there's reference material on C. Getting K%26amp;R's book also helps.
Reply:Ummm... Choice a. This is because that any parameter passed without a pointer or by reference (I'm assuming you're referring to C++ here) will be copied as an automatic storage class variable and can be called by the function within its scope by the formal variable name.
Reply:c
Reply:this would depend on which language you are coding in


in c, the answer is a


in java, the answer is c


No comments:

Post a Comment