Interview Preparation Exam  >  Interview Preparation Notes  >  Placement Papers - Technical & HR Questions  >  Pointers (Part - 2), C Programming Interview Questions

Pointers (Part - 2), C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation PDF Download

5. What is a void pointer?

void pointer is a C convention for "a raw address." The compiler has no idea what type of object a voidpointer "really points to." If you write

int *ip;

ip points to an int. If you write

void *p;

p doesn't point to a void!

In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don't even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it.)


6. When is a void pointer used?

void pointer is used for working with raw memory or for passing a pointer to an unspecified type.

Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory.

For example, strcpy() is used to copy data from one string to another, and strncpy() is used to copy at most a certain length string to another:

char *strcpy( char *str1, const char *str2 );

char *strncpy( char *str1, const char *str2, size_t n );

memcpy() is used to move data from one location to another:

void *memcpy( void *addr1, void *addr2, size_t n );

void pointers are used to mean that this is raw memory being copied. NUL characters (zero bytes) aren't significant, and just about anything can be copied. Consider the following code:

 

#include "thingie.h"    /* defines struct thingie */
struct thingie  *p_src, *p_dest;
/* ... */
memcpy( p_dest, p_src, sizeof( struct thingie) * numThingies );

 

This program is manipulating some sort of object stored in a struct thingie. p1 and p2 point to arrays, or parts of arrays, of struct thingies. The program wants to copy numThingies of these, starting at the one pointed to by p_src, to the part of the array beginning at the element pointed to by p_destmemcpy() treats p_src and p_dest as pointers to raw memory; sizeof( struct thingie) * numThingies is the number of bytes to be copied.

 

7. Can you subtract pointers from each other? Why would you?

If you have two pointers into the same array, you can subtract them. The answer is the number of elements between the two elements.

Consider the street address analogy presented in the introduction of this chapter. Say that I live at 118 Fifth Avenue and that my neighbor lives at 124 Fifth Avenue. The "size of a house" is two (on my side of the street, sequential even numbers are used), so my neighbor is (124-118)/2 (or 3) houses up from me. (There are two houses between us, 120 and 122; my neighbor is the third.) You might do this subtraction if you're going back and forth between indices and pointers.

You might also do it if you're doing a binary search. If p points to an element that's before what you're looking for, and q points to an element that's after it, then (q-p)/2+p points to an element between p and q. If that element is before what you want, look between it and q. If it's after what you want, look between p and it.

(If it's what you're looking for, stop looking.)

You can't subtract arbitrary pointers and get meaningful answers. Someone might live at 110 Main Street, but I can't subtract 110 Main from 118 Fifth (and divide by 2) and say that he or she is four houses away!

If each block starts a new hundred, I can't even subtract 120 Fifth Avenue from 204 Fifth Avenue. They're on the same street, but in different blocks of houses (different arrays).

C won't stop you from subtracting pointers inappropriately. It won't cut you any slack, though, if you use the meaningless answer in a way that might get you into trouble.

When you subtract pointers, you get a value of some integer type. The ANSI C standard defines a typedef,ptrdiff_t, for this type. (It's in <stddef.h>.) Different compilers might use different types (int or long or whatever), but they all define ptrdiff_t appropriately.

Below is a simple program that demonstrates this point. The program has an array of structures, each 16 bytes long. The difference between array[0] and array[8] is 8 when you subtract struct stuff pointers, but 128(hex 0x80) when you cast the pointers to raw addresses and then subtract.

If you subtract 8 from a pointer to array[8], you don't get something 8 bytes earlier; you get something 8 elements earlier.

 

#include <stdio.h>
#include <stddef.h>
struct stuff {
        char    name[16];
        /* other stuff could go here, too */
};
struct stuff array[] = {
        { "The" },
        { "quick" },
        { "brown" },
        { "fox" },
        { "jumped" },
        { "over" },
        { "the" },
        { "lazy" },
        { "dog." },
        { "" }
};
int main()
{
        struct stuff    *p0 = & array[0];
        struct stuff    *p8 = & array[8];
        ptrdiff_t       diff = p8 - p0;
        ptrdiff_t       addr_diff = (char*) p8 - (char*) p0;
        /* cast the struct stuff pointers to void* */
        printf("& array[0] = p0 = %P\n", (void*) p0);
        printf("& array[8] = p8 = %P\n", (void*) p8);
        /* cast the ptrdiff_t's to long's
        (which we know printf() can handle) */
        printf("The difference of pointers is %ld\n",
          (long) diff);
        printf("The difference of addresses is %ld\n",
          (long) addr_diff);
        printf("p8 - 8 = %P\n", (void*) (p8 - 8));
        
        printf("p0 + 8 = %P (same as p8)\n", (void*) (p0 + 8));
        return 0;  
}

 

8. Is NULL always defined as 0(zero)?

NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a voidpointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can't always tell when a pointer is needed).

 

9. Is NULL always equal to 0(zero)?

The answer depends on what you mean by "equal to." If you mean "compares equal to," such as

 

if ( /* ... */ )
{
     p = NULL;
}
else
{
     p = /* something else */;
}
/* ... */
if ( p == 0 )

 

then yes, NULL is always equal to 0. That's the whole point of the definition of a null pointer.

If you mean "is stored the same way as an integer zero," the answer is no, not necessarily. That's the most common way to store a null pointer. On some machines, a different representation is used.

The only way you're likely to tell that a null pointer isn't stored the same way as zero is by displaying a pointer in a debugger, or printing it. (If you cast a null pointer to an integer type, that might also show a nonzero value.)

 

10. What does it mean when a pointer is used in an if statement?

Any time a pointer is used as a condition, it means "Is this a non-null pointer?" A pointer can be used in an if, whilefor, or do/while statement, or in a conditional expression. It sounds a little complicated, but it's not.

Take this simple case:

 

if ( p )
{
     /* do something */
}
else
{
     /* do something else */
}

 

An if statement does the "then" (first) part when its expression compares unequal to zero. That is,

if ( /* something */ )

is always exactly the same as this:

if ( /* something */ != 0 )

That means the previous simple example is the same thing as this:

 

if ( p != 0 )
{
     /* do something (not a null pointer) */
}
else
{
     /* do something else (a null pointer) */
}

 

This style of coding is a little obscure. It's very common in existing C code; you don't have to write code that way, but you need to recognize such code when you see it.


11. Can you add pointers together? Why would you?

No, you can't add pointers together. If you live at 1332 Lakeview Drive, and your neighbor lives at 1364 Lakeview, what's 1332+1364? It's a number, but it doesn't mean anything. If you try to perform this type of calculation with pointers in a C program, your compiler will complain.

The only time the addition of pointers might come up is if you try to add a pointer and the difference of two pointers:

p = p + p2 - p1;

which is the same thing as this:

p = (p + p2) - p1.

Here's a correct way of saying this:

p = p + ( p2 - p1 );

Or even better in this case would be this example:

p += p2 - p1;

 

12. How do you use a pointer to a function?

The hardest part about using a pointer-to-function is declaring it. Consider an example. You want to create a pointer, pf, that points to the strcmp() function. The strcmp() function is declared in this way:

int strcmp( const char *, const char * )

To set up pf to point to the strcmp() function, you want a declaration that looks just like the strcmp()function's declaration, but that has *pf rather than strcmp:

int (*pf)( const char *, const char * );

Notice that you need to put parentheses around *pf. If you don't include parentheses, as in

int *pf( const char *, const char * ); /* wrong */

you'll get the same thing as this:

(int *) pf( const char *, const char * ); /* wrong */

That is, you'll have a declaration of a function that returns int*.

After you've gotten the declaration of pf, you can #include <string.h> and assign the address of strcmp()to pf:

pf = strcmp;

or

pf = & strcmp; /* redundant & */

You don't need to go indirect on pf to call it:

if ( pf( str1, str2 ) > 0 ) /* ... */

The document Pointers (Part - 2), C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation is a part of the Interview Preparation Course Placement Papers - Technical & HR Questions.
All you need of Interview Preparation at this link: Interview Preparation
85 docs|57 tests

Top Courses for Interview Preparation

Explore Courses for Interview Preparation exam

Top Courses for Interview Preparation

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Extra Questions

,

Previous Year Questions with Solutions

,

past year papers

,

ppt

,

video lectures

,

Important questions

,

Pointers (Part - 2)

,

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

Exam

,

study material

,

Pointers (Part - 2)

,

Free

,

Viva Questions

,

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

shortcuts and tricks

,

mock tests for examination

,

practice quizzes

,

Pointers (Part - 2)

,

MCQs

,

Summary

,

pdf

,

Objective type Questions

,

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

Sample Paper

,

Semester Notes

;