C Inetrview Question and Answer Set-5

| Thursday 9 June 2011

Arrays and Pointers

5.1: I had the definition char a[6] in one source file, and in another I declared extern char a[]. Why did it work?

The declaration extern char a[] simply matches the actual definition. The type ``array-of-type-T'' is the same as ``array-of-type-T.'' Go ahead and use extern char a[]. (For greater portability, use it in both files, not only in one of them.)

5.2: But I heard that char a[] was different from char a[6].

This is true. However, the declaration a[] is compatible with the definition a[6].

5.3: So what is meant by the ``equivalence of pointers and arrays'' in C?

Very little.

5.4: Then why are array and pointer declarations interchangeable as function formal parameters?

Classism. We consider arrays ``second class objects''. They don't vote, and they get treated as pointers. Additionally, they're merely objects, not citizens. Marx wrote about this a lot.

5.5: Why doesn't sizeof properly report the size of an array which is a parameter to a function?

Part of the ANSI conspiracy to restrict people to passing pointers; this was undertaken after the first discovery that passing large arrays recursively could cause crashes. Since then, with the passing of MS-DOS, it has become a non-issue; since all serious machines have virtual memory, you can pass as much data as you want on the stack without detectable problems.

5.6: Someone explained to me that arrays were really just constant pointers.

Cool. Someone I know says he saw Elvis in a local bar.
5.7: Practically speaking, what is the difference between arrays and pointers?
About the difference between alcohol and marijuana; they have different characteristics, and that's not a problem if you don't mix them too carelessly.

5.8: I came across some ``joke'' code containing the ``expression'' 5["abcdef"]. How can this be legal C?

It was added to allow people to avoid the character constant 'f' which may not be available on some systems. (Actually, it's a side-effect of the equivalence of arrays and pointers.)

5.9: How would I initialize an entire array from standard input?

You have to use a loop. For instance, the following code reads the numbers zero through 99 into the array a.
for (i = 0; i < 100; ++i)
        a[i] = (scanf, ("%d", i));
Make sure to include <stdio.h>, or this may not work.

0 comments:

Post a Comment

Popular Posts

Company Placement Papers

 

Copyright © 2010 All Question Papers Blogger Template by Dzignine