C_programV1 Global Edge

Embed Size (px)

DESCRIPTION

C programming interview questions

Citation preview

  • C Interview questions 1

    C Interview questions with Examples - version 1.0

    By,Girish Kumar SSoftware EngineerGlobal Edge Software Ltd.Bangalore,560003Mob: 9986069810

    MailId:[email protected]

    GESL confidential

  • C Interview questions 2

    CONTENTS

    1. Compilation steps2. Memory Layout of C program3. Stack Frame4. Bitwise Programs5. String Programs6. Pointers Related Programs7. Data structure Programs8.

    GESL confidential

  • C Interview questions 3

    1. Compilation Steps

    GESL confidential

    C program

    Preprossor

    Compiler: Lexical AnalyzerParser Optimizer Code generator

    Assembler

    Library(libc.a)Linker

    Executable File

    Other Object modules

    test.c

    test.o

    a.out

    test.s

    test.i

  • C Interview questions 4

    2. Memory Layout of C program.

    GESL confidential

    Arguments and Environment variables

    Stack(grow downwards)

    Heap(grow upwards)

    Data(initialized static data)

    BSS(uninitialized static data)

    Code(program instructions)Low Addr

    High Addr

  • C Interview questions 5

    3. Frame Pointer(FP) and Stack Pointer(SP):

    These two register holds the address of a memory location on the stack. While the stack pointer is a moving reference to a single cell(it's modified with each push or pop). The frame pointer is used for maintaining a subroutine's variables. All local variables are maintained on the stack in a contiguous block created when a subroutine is entered(at run-time). The subroutine's arguments are also kept on the stack, in the same memory block as the variables. This block of memory is a subroutine's stack frame, and the frame pointer is used to reference the various memory locations comprised by the stack frame.

    Stack frames are created when a subroutine is entered, they are deleted when the subroutine returns. Consequently the same area of memory(the stack) is constantly recycled as various subroutines execute. That is, several subroutines use the same part of the stack for their local variables.

    Ex:

    int p1 = 1, p2 = 2, p3 = 3;

    foo(int p1, int p2, int p3){

    int v1, v2, v3;

    return 0;}

    main(){

    foo(p1, p2, p3);}

    Half of the stack frame is created by the calling subroutine-main() in this case and other half by foo() itself. Main() passes arguments to foo() by pushing them onto the stack; these pushed arguments are the first part of the new stack frame.The arguments are pushed from right to left(p3 is pushed first. In C , all argument passing (except for arrays) is done by value. That is , the value of the variable p3 is passed to foo(), not p3 itself.

    The stack:

    GESL confidential

  • C Interview questions 6

    Fig: The partially created stack frame for foo(). The contents of the original variables have been copied here.

    Next, the subroutine foo() is actually called. This call puts the return address on to the stack.

    Fig : The stack immediately after foo() is Entered.(we are now in subroutine foo() but have not yet executed any code in foo().)

    The first thing that foo() does is preserve the existing frame pointer by pushing it. Then it copies the current stack pointer into the frame pointer.

    Fig : The stack after the old stack frame is saved.

    Next, foo() allocates space for its own local variables. This space is carved out of the stack by subtracting a suitably large constant from the stack pointer.

    GESL confidential

  • C Interview questions 7

    Fig: The Remainder of the stack frame is created

    When the subroutine returns. Foo() has to delete all the parts of the stack frame that it created. Local variables are deleted by copying the current value of the frame pointer into the stack pointer, making the stack pointer point to the same place as the frame pointer.

    Fig: The local variables are deleted.

    GESL confidential

  • C Interview questions 8

    Next, the old frame pointer is restored by popping its old value off the stack.

    Fig: The old frame pointer is restored with a pop

    Then foo() executes a RET instruction, returning to main() and popping its return address off the stack. The stack now looks just as it did before foo() was called.

    Fig: The stack after foo() returns.

    Now, main() throws away the stack variables associated with the arguments. Since the arguments to a called subroutine aren't used by main(), it doesn't bother to pop them off the stack back into the original variables.

    GESL confidential

  • C Interview questions 9

    Entire stack frame diagram of main() program.

    Return value from the stack is returned by register(accumulator). If you are not returning any thing the garbage will be stored in register.

    GESL confidential

    v3

    v2

    v1

    Old FP

    Return address

    p2

    Old FP

    Return address

    p3

    p1

    argc

    argv

  • C Interview questions 10

    4. Bitwise programs:

    1.adding two integer

    int add(int a, int b){

    int temp = 0;while (b) {

    temp = a ^ b;b = (a & b)

  • C Interview questions 11

    b >>= 1;}

    return result;}------------------------------------------------------4. Bits size

    int main(){

    unsigned char i = 0;int count = 0;

    i = ~i;

    while (i) {i = i >> 1;count++;

    }

    printf(" %d \n", count);

    exit(EXIT_SUCCESS);}--------------------------------------------------------5. Bits reverse

    int bit_rev(int num){

    unsigned int temp = 0;int i;

    for (i = ((sizeof(num) * 8)) - 1; i; i--) {temp = temp | (num & 01);temp = 1;

    }temp = temp | (num & 01);

    return temp;}----------------------------------------------------------6. Bits count

    int fn_bits1(int num){

    int i;

    for (i = 0; num != 0; num >>= 1) {if (num & 1)

    i++;}return i;

    }

    GESL confidential

  • C Interview questions 12

    -----------------------------------------------------------7. atoi

    int atoi_b(char str[]){

    int i = 0;

    while (*str) {i = (i

  • C Interview questions 13

    }-------------------------------------

    11.convert from one Endian to another.

    int myreversefunc(int num){

    int byte0, byte1, byte2, byte3;

    byte0 = (num & x000000FF) >> 0 ;byte1 = (num & x0000FF00) >> 8 ;byte2 = (num & x00FF0000) >> 16 ;byte3 = (num & xFF000000) >> 24 ;

    return((byte0

  • C Interview questions 14

    {a^=b^=a^=b;

    printf("a = %d b = %d \n", a, b);}

    void swap2(int a, int b){

    a = a ^ b;b = a ^ b;a = a ^ b;

    printf("a = %d b = %d \n", a, b);}

    ----------------------------------------------------3. String reverse

    void reverse(char *s){

    fn_reverse(s, 0, strlen(s));}

    void fn_reverse(char s[], int i, int len){

    int c, j;j = len - (i+ 1);if (i < j) {

    c = s[i];s[i] = s[j];s[j] = c;fn_reverse(s, ++i, len);

    }

    }

    ---------------------------------------------------4. Even or odd numbers

    #define CHECK(x) ((x & 01) ? 0 : 1)----------------------------------------------------5. Biggest of two numbers

    #define MAX(a, b) (((a) > (b)) ? (a) : (b))

    ------------------------------------------------------------6.

    #define myisalnum(c) ((c >= 'a' && c = 'A' && c = '0' && c = 'a' && c = 'A' && c

  • C Interview questions 15

    #define myisdigit(c) ((c >= '0' && c = '0' && c = 'a' && c = 'A' && c = 0x20) && (c = 'A' && c = '\0') && (c = 'a' && c = 1) ? 1 : 0#define lit_big(n) ( *(char *) &n) ? 0 : 1

    #define larg(a,b,c,d) ((a > b) ? ((a > c) ? ((a > d) ? a : d) : ((c > d) ? c : d)) : ((b > c) ? ((b > d) ? b : d) : ((c > d) ? c : d)))

    #define mysizeof(x) ((int)(&x + 1) - (int)&x)

    #define mystrindex(s,t,i) { \int j, k, flag = 0;\for(i = 0; s[i] != '\0'; i++) {\

    for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)\

    ;\if(k > 0 && t[k] == '\0') { flag = 1; break; }

    \}\if(!flag) i = -1; \

    }\--------------------------------------------------------------------8. Factorial of a number

    int fact(int num){

    if (num == 1)return 1;

    else return (num * fact(num - 1));

    }-----------------------------------------------------9. count lines, words, and characters in input

    main(){

    int c, nl, nw, nc, state;state = OUT;

    GESL confidential

  • C Interview questions 16

    nl = nw = nc = 0;

    while ((c = getchar()) != EOF) {++nc;

    if (c == '\n')++nl;

    if (c == ' ' || c == '\n' || c = '\t')state = OUT;

    else if (state == OUT) {state = IN;++nw;

    }}printf("%d %d %d\n", nl, nw, nc);

    }--------------------------------------------------------9. String length

    int strlen(char s[]){

    int i;

    while (s[i] != '\0')++i;

    return i;}

    int strlen(char *s){

    int n;

    for (n = 0; *s != '\0', s++)n++;

    return n;}

    int strlen(char *s){

    char *p = s;

    while (*p != '\0')p++;

    return p - s;}--------------------------------------------------------

    10. lower: convert c to lower case; ASCII only

    int lower(int c)

    GESL confidential

  • C Interview questions 17

    {if (c >= 'A' && c

  • C Interview questions 18

    if (s[i] == '+' || s[i] == '-') /* skip sign */i++;

    for (n = 0; isdigit(s[i]); i++)n = 10 * n + (s[i] - '0');

    return sign * n;}------------------------------------------------------14. itoa

    void reverse(char s[]){

    int c, i, j;

    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {c = s[i];s[i] = s[j];s[j] = c;

    }}

    void itoa(int n, char s[]){

    int i, sign;

    if ((sign = n) < 0) /* record sign */n = -n; /* make n positive */i = 0;

    do { /* generate digits in reverse order */s[i++] = n % 10 + '0'; /* get next digit */

    } while ((n /= 10) > 0); /* delete it */

    if (sign < 0)s[i++] = '-';s[i] = '\0';

    reverse(s);}------------------------------------------------------15. trim: remove trailing blanks, tabs, newlines

    int trim(char s[]){

    int n;

    for (n = strlen(s)-1; n >= 0; n--)if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')break;

    s[n+1] = '\0';return n;

    GESL confidential

  • C Interview questions 19

    }------------------------------------------------------------16. qsort: sort v[left]...v[right] into increasing order

    void qsort(int v[], int left, int right){

    int i, last;

    void swap(int v[], int i, int j);

    if (left >= right) /* do nothing if array contains */return; /* fewer than two elements */

    swap(v, left, (left + right)/2); /* move partition elem */

    last = left; /* to v[0] */

    for (i = left + 1; i

  • C Interview questions 20

    s++;t++;

    }}

    void strcpy(char *s, char *t){

    while ((*s++ = *t++) != '\0');

    }

    void strcpy(char *s, char *t){

    while (*s++ = *t++);

    }--------------------------------------------------------18. strcmp: return t

    int strcmp(char *s, char *t){

    int i;

    for (i = 0; s[i] == t[i]; i++)if (s[i] == '\0')

    return 0;

    return s[i] - t[i];}

    int strcmp(char *s, char *t){

    for ( ; *s == *t; s++, t++)if (*s == '\0')

    return 0;

    return *s - *t;}

    int strcmp(const char * cs,const char * ct){ register signed char __res;

    while (1) { if ((__res = *cs - *ct++) != 0 || !*cs++) break; }

    return __res;}

    GESL confidential

  • C Interview questions 21

    --------------------------------------------------------------19. binsearch: find word in tab[0]...tab[n-1]

    int binsearch(char *word, struct key tab[], int n){

    int cond;int low, high, mid;

    low = 0;high = n - 1;

    while (low 0)low = mid + 1;

    elsereturn mid;

    }

    return -1;}----------------------------------------------------------------20./** * strnicmp - Case insensitive, length-limited string comparison * @s1: One string * @s2: The other string * @len: the maximum number of characters to compare */

    int strnicmp(const char *s1, const char *s2, size_t len){ /* Yes, Virginia, it had better be unsigned */ unsigned char c1, c2;

    c1 = 0; c2 = 0; if (len) { do { c1 = *s1; c2 = *s2; s1++; s2++; if (!c1) break; if (!c2) break; if (c1 == c2) continue; c1 = tolower(c1); c2 = tolower(c2);

    GESL confidential

  • C Interview questions 22

    if (c1 != c2) break; } while (--len); } return (int)c1 - (int)c2;}---------------------------------------------------------21.strncpy

    char * strncpy(char * dest,const char *src,size_t count){ char *tmp = dest;

    while (count-- && (*dest++ = *src++) != '\0') /* nothing */;

    return tmp;}------------------------------------------------------------22.

    char * strcat(char * dest, const char * src){ char *tmp = dest;

    while (*dest) dest++; while ((*dest++ = *src++) != '\0') ;

    return tmp;}--------------------------------------------------------23.

    char * strncat(char *dest, const char *src, size_t count){ char *tmp = dest;

    if (count) { while (*dest) dest++; while ((*dest++ = *src++)) { if (--count == 0) { *dest = '\0'; break; } } }

    return tmp;}------------------------------------------------------------24.

    GESL confidential

  • C Interview questions 23

    /** * strchr - Find the first occurrence of a character in a string * @s: The string to be searched * @c: The character to search for */char * strchr(const char * s, int c){ for(; *s != (char) c; ++s) if (*s == '\0') return NULL; return (char *) s;}--------------------------------------------------------25.

    /** * strrchr - Find the last occurrence of a character in a string * @s: The string to be searched * @c: The character to search for */char * strrchr(const char * s, int c){ const char *p = s + strlen(s); do { if (*p == (char)c) return (char *)p; } while (--p >= s); return NULL;}----------------------------------------------------------26.

    size_t strnlen(const char * s, size_t count){ const char *sc;

    for (sc = s; count-- && *sc != '\0'; ++sc) /* nothing */; return sc - s;}---------------------------------------------------27.

    /** * strspn - Calculate the length of the initial substring of @s which only * contain letters in @accept * @s: The string to be searched * @accept: The string to search for */size_t strspn(const char *s, const char *accept){ const char *p; const char *a;

    GESL confidential

  • C Interview questions 24

    size_t count = 0;

    for (p = s; *p != '\0'; ++p) { for (a = accept; *a != '\0'; ++a) { if (*p == *a) break; } if (*a == '\0') return count; ++count; }

    return count;}-------------------------------------------------------------------------

    28./** * strpbrk - Find the first occurrence of a set of characters * @cs: The string to be searched * @ct: The characters to search for */char * strpbrk(const char * cs,const char * ct){ const char *sc1,*sc2;

    for( sc1 = cs; *sc1 != '\0'; ++sc1) { for( sc2 = ct; *sc2 != '\0'; ++sc2) { if (*sc1 == *sc2) return (char *) sc1; } } return NULL;}--------------------------------------------------------------29.

    /** * strtok - Split a string into tokens * @s: The string to be searched * @ct: The characters to search for * * WARNING: strtok is deprecated, use strsep instead. */

    char * ___strtok;

    char * strtok(char * s,const char * ct){ char *sbegin, *send;

    sbegin = s ? s : ___strtok; if (!sbegin) { return NULL;

    GESL confidential

  • C Interview questions 25

    } sbegin += strspn(sbegin,ct); if (*sbegin == '\0') { ___strtok = NULL; return( NULL ); } send = strpbrk( sbegin, ct); if (send && *send != '\0') *send++ = '\0'; ___strtok = send; return (sbegin);}-----------------------------------------------------------------30.

    /** * strsep - Split a string into tokens * @s: The string to be searched * @ct: The characters to search for * * strsep() updates @s to point after the token, ready for the next call. * * It returns empty tokens, too, behaving exactly like the libc function * of that name. In fact, it was stolen from glibc2 and de-fancy-fied. * Same semantics, slimmer shape. ;) */char * strsep(char **s, const char *ct){ char *sbegin = *s, *end;

    if (sbegin == NULL) return NULL;

    end = strpbrk(sbegin, ct); if (end) *end++ = '\0'; *s = end;

    return sbegin;}-----------------------------------------------------

    31.

    void * memset(void * s,int c,size_t count){ char *xs = (char *) s;

    while (count--) *xs++ = c;

    return s;}---------------------------------------------

    GESL confidential

  • C Interview questions 26

    32.

    void * memcpy(void * dest,const void *src,size_t count){ char *tmp = (char *) dest, *s = (char *) src;

    while (count--) *tmp++ = *s++;

    return dest;}--------------------------------------------------33.

    void * memmove(void * dest,const void *src,size_t count){ char *tmp, *s;

    if (dest

  • C Interview questions 27

    * @size: The size of the area. * * returns the address of the first occurrence of @c, or 1 byte past * the area if @c is not found */void * memscan(void * addr, int c, size_t size){ unsigned char * p = (unsigned char *) addr;

    while (size) { if (*p == c) return (void *) p; p++; size--; } return (void *) p;}----------------------------------------------------------------------36.

    /** * strstr - Find the first substring in a %NUL terminated string * @s1: The string to be searched * @s2: The string to search for */char * strstr(const char * s1,const char * s2){ int l1, l2;

    l2 = strlen(s2); if (!l2) return (char *) s1; l1 = strlen(s1); while (l1 >= l2) { l1--; if (!memcmp(s1,s2,l2)) return (char *) s1; s1++; } return NULL;}-----------------------------------------------------------------------37.

    /** * memchr - Find a character in an area of memory. * @s: The memory area * @c: The byte to search for * @n: The size of the area. * * returns the address of the first occurrence of @c, or %NULL * if @c is not found */void *memchr(const void *s, int c, size_t n)

    GESL confidential

  • C Interview questions 28

    { const unsigned char *p = s; while (n-- != 0) { if ((unsigned char)c == *p++) { return (void *)(p-1); } } return NULL;}---------------------------------------------------------38. GCD

    int gcd(int m, int n){

    while(m != n) /* Be in the loop till m & n are equal */{

    if(m > n)m = m - n;

    elsen = n - m;

    }

    return m;}

    int gcd(int m, int n){

    int r;

    while(n != 0){ r = m % n; m = n; n = r;}

    return m;}

    -----------------------------------------------

    39. Fibonacci number

    0, 1, 1, 2, 3, 5, 8, 13,...........

    int fib(int n){

    if(n == 1) return 0;

    if(n == 2) return 1;

    return fib(n - 1) + fib(n - 2);

    GESL confidential

  • C Interview questions 29

    }

    int fib(int n){

    int f[n+1];

    f[1] = f[2] = 1;

    printf("\nf[1] = %d", f[1]);printf("\nf[2] = %d", f[2]);

    for (int i = 3; i

  • C Interview questions 30

    if(head == (mynode *)0){

    return;}

    p = head;q = p->next;p->next = (mynode *)0;

    while (q != (mynode *)0){

    r = q->next;q->next = p;p = q;q = r;

    }head = p;

    }

    mynode* reverse_recurse(mynode *root){

    if(root->next!=(mynode *)0){

    reverse_recurse(root->next);root->next->next=root;return(root);

    }else{

    head=root;}

    }------------------------------------------42. Program to find prime number

    main() { int num, tmp, count, i;

    printf("enter the number to be checked"); scanf("%d",&n);

    for(i=1;i

  • C Interview questions 31

    { printf("the given number is prime");} else printf("the given number is not prime");

    }---------------------------------------------43. Find loop in a linked list

    Visited flag:Have a visited flag in each node of the linked list.

    Flag it as visited when you reach the node. When you reach a nodeand the flag is already flagged as visited, then you know thereis a loop in the linked list.

    Fastest method:Have 2 pointers to start of the linked list. Increment one

    pointer by 1 node and the other by 2 nodes. If there's a loop,the 2nd pointer will meet the 1st pointer somewhere. If it does,then you know there's one.

    Here is some code

    p=head;q=head->next;

    while(p!=NULL && q!=NULL){

    if(p==q){ //Loop detected! exit(0);}

    p=p->next;q=(q->next)?(q->next->next):q->next;

    }// No loop.-------------------------------------------------------44. Swapping a nibbles

    unsigned char swap_nibbles(unsigned char c){

    unsigned char temp1, temp2;

    temp1 = c & 0x0F;temp2 = c & 0xF0;temp1= temp1 > 4;

    return (temp2|temp1); //adding the bits}------------------------------------------------------

    GESL confidential

  • C Interview questions 32

    45.

    float a=3.14; float **z;

    float **y; float ***x;

    float ****v; float ****w;

    float **fun1(float *);float ****fun2(float ***);

    main(){

    z = fun1(&a); printf("%f", **z);

    }

    float **fun1(float *z){

    y = &z; v = func2(&y);

    return (**v);}

    float ****fun2(float ***x){

    w = &x; return (w);}

    -----------------------------------------------46. Pointers and two dimensional arrays

    stud[5][2] = { {1234, 56}, {1212, 33}, {1434, 80}, {1312, 78}, {1203, 75}

    };

    for(i = 0; i

  • C Interview questions 33

    a[3][4] = { 1,2,3,4, 5,6,7,8, 9,0,1,6 };

    If I call display(a, 3, 4) or show(a, 3, 4);

    display(int *q, int row, int col) {

    for(i = 0; i < row; i++) {

    for(j = 0; j < col; j++) {

    printf("%d", *(q + i * col + j)); } } }

    show(int (*q)[4], int row , int col) {

    int *p;

    for(i = 0; i < row; i++) {

    p = q + 1;

    for(j = 0; j < col; j++) {

    printf("%d", *(p + j)); } } }

    print(int q[][4], int row, int col);-------------------------------------------------------47. Three Dimensional arrays

    a[2][3][2] = { { {2, 4}, {7, 8}, {3, 4},},{ {2, 2}, {2, 3}, {3, 4},}

    };

    GESL confidential

  • C Interview questions 34

    If I call display(a, 2, 3, 2) or show(a, 2, 3, 2);

    display(int *q, int ii, int jj, int kk){

    for(i = 0; i

  • C Interview questions 35

    int (*fun2())[COL];int *p;

    int (*fun2())[COL] {

    static int b[ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6 };

    return b; }

    int (*c)[ROW][COL];int (*fun3()){ROW][COL];

    int (*fun3())[ROW][COL] {

    static int c[ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6 };

    return (int(*)[ROW][COL]) c;

    }---------------------------------------------------------Returning 3D array from function:

    SET = 2 ROW = 3 COL = 4

    int *a;int *fun1();

    int *fun1() {

    static int a[SET][ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6 };

    return (int *)a; }

    int (*b)[COL];int (*fun2())[COL];int *p;

    int (*fun2())[COL] {

    static int b[SET][ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6

    GESL confidential

  • C Interview questions 36

    };

    return (int(*)[COL]) b; }

    int (*c)[ROW][COL];int (*fun3()){ROW][COL];

    int (*fun3())[ROW][COL] {

    static int c[SET][ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6 };

    return (int(*)[ROW][COL]) c;

    }

    int (*d)[SET][ROW][COL];int (*fun4())[SET][ROW][COL];

    int (*fun4())[SET][ROW][COL] {

    static int c[SET][ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 6 };

    return (int (*)[SET][ROW][COL])d; }----------------------------------------------------

    char str1[] = "Hello";char str2[10];

    char *s = "Good morning";char *q;

    str2 = str1; /* error */q = s; /* works *?

    ---------------------------

    char *p = "Hello" ; /* pointer is variable, so is string */*P = 'M'; /* works */p = "Bye"; /* works */

    const char *q = "Hello"; /* string is constant pointer is not */*q = 'M'; /* error */q = "Bye"; /* works */

    char const *s = "Hello" ; /* string is constant pointer is not */*s = 'M'; /* error */s = "Bye"; /* works */

    GESL confidential

  • C Interview questions 37

    char *const t = "Hello"; /* pointer is constant string is not */*t = 'M'; /* works */t = "Bye"; /* error */

    const char * const u = "Hello"; /* string is constant , so is pointer */*u = 'M'; /* error */u = "Bye"; /* error */---------------------------------------------

    Array of pointer to strings:

    char *names[] = { "girish", "mahesh", "ravi", "arun", "gopal"};

    ---------------------------------------------

    ---------------------------------------------------######### Function pointers ##################################

    Function Pointers are pointers, i.e. variables, which point to the address of a function.

    /* function returning pointer to int */int *func(int a, float b);

    /* pointer to function returning int */int (*func)(int a, float b);

    You can call the function using one of two forms:

    (*func)(1,2);/* or */func(1,2);-----------------------------------void func(int);

    main(){ void (*fp)(int);

    fp = func;

    (*fp)(1); fp(2);

    exit(EXIT_SUCCESS);}

    voidfunc(int arg){ printf("%d\n", arg);

    GESL confidential

  • C Interview questions 38

    }--------------------------------

    you can have an array of pointers to functions, with declaration and use like this:

    void (*fparr[])(int, float) = { /* initializers */ };/* then call one */

    fparr[5](1, 3.4);---------------------------------------typedef void (*fn)(void);

    void a(){

    printf("HI AAA\n");}

    int main(){

    fn fun;fun = a;fun();printf(" HI \n");

    exit(EXIT_SUCCESS); }------------------------------------int (*fun)(int, int);

    int add(int a, int b){

    return a + b;}

    int sub(int a, int b){

    return a - b;}

    int function(int (*fun) (int, int), int x, int y){

    return fun(x, y);}

    int main(){

    printf(" add = %d \n", function(add, 10, 20));printf(" sub = %d \n", function(sub, 10, 20));

    exit(EXIT_SUCCESS);}---------------------------------------------------

    GESL confidential

  • C Interview questions 39

    typedef int (*fun)(int, int);

    int add(int a, int b){

    return a + b;}

    int sub(int a, int b){

    return a - b;}

    int function(fun fun1, int x, int y){

    return fun1(x, y);}

    int main(){

    printf(" add = %d \n", function(add, 10, 20));printf(" sub = %d \n", function(sub, 10, 20));

    exit(EXIT_SUCCESS);}-------------------------------------------------------typedef void (*fun)(char str[]);void fn_rev(char str[]);

    int main(){

    char str[10];fun fun1;

    printf(" Enter name \n");scanf("%s", str);fun1 = fn_rev;(*fun1)(str);printf(" string = %s \n", str);

    exit(EXIT_SUCCESS);}

    void fn_rev(char str[]){

    int c, i, j;

    for (i = 0, j = strlen(str) - 1; i < j; i++, j--) {c = str[i];str[i] = str[j];str[j] = c;

    }}-------------------------------------------------int sum(int a, int b);

    GESL confidential

  • C Interview questions 40

    int subtract(int a, int b);int mul(int a, int b);int div(int a, int b);

    int (*p[4]) (int x, int y);

    or

    /* initialize the pointer array */int (*p[4]) (int x, int y) = { sum, subtract, mul, div} ;

    int main(void){ int result; int i, j, op;

    p[0] = sum; /* address of sum() */ p[1] = subtract; /* address of subtract() */ p[2] = mul; /* address of mul() */ p[3] = div; /* address of div() */

    printf("Enter two numbers: "); scanf("%d %d", &i, &j); printf("0: Add, 1: Subtract, 2: Multiply, 3: Divide\n"); do { printf("Enter number of operation: "); scanf("%d", &op); } while(op3);

    result = (*p[op]) (i, j); printf("%d", result);

    return 0;}--------------------------------------------------------------void check(char *a, char *b,int (*cmp)(const char *, const char *));

    int main(void){ char s1[80]= "asdf", s2[80]="asdf"; int (*p)(const char *, const char *);

    p = strcmp;

    check(s1, s2, p);

    return 0;}

    GESL confidential

  • C Interview questions 41

    void check(char *a, char *b,int (*cmp)(const char *, const char *)){ printf("Testing for equality.\n"); if(!(*cmp)(a, b)) { printf("Equal"); }else { printf("Not Equal"); }}-----------------------------------------------------------------char **argv

    argv: pointer to char

    int (*daytab)[13]daytab: pointer to array[13] of int

    int *daytab[13]daytab: array[13] of pointer to int

    void *comp()comp: function returning pointer to void

    void (*comp)()comp: pointer to function returning void

    char (*(*x())[])()x: function returning pointer to array[] ofpointer to function returning char

    char (*(*x[3])())[5]x: array[3] of pointer to function returningpointer to array[5] of char

    -----------------------------------------------------------------########## Varargs ###################################

    #include #include

    extern char *itoa(int, char *, int);

    void myprintf(const char *fmt, ...){const char *p;va_list argp;int i;char *s;char fmtbuf[256];

    va_start(argp, fmt);

    for(p = fmt; *p != '\0'; p++){

    GESL confidential

  • C Interview questions 42

    if(*p != '%'){putchar(*p);continue;}

    switch(*++p){case 'c':

    i = va_arg(argp, int);putchar(i);break;

    case 'd':i = va_arg(argp, int);s = itoa(i, fmtbuf, 10);fputs(s, stdout);break;

    case 's':s = va_arg(argp, char *);fputs(s, stdout);break;

    case 'x':i = va_arg(argp, int);s = itoa(i, fmtbuf, 16);fputs(s, stdout);break;

    case '%':putchar('%');break;

    }}

    va_end(argp);}

    1-> va_list argp;

    This line declares a variable, argp

    2-> va_start(argp, fmt);

    This line initializes argp and initiates the processing of the argument list

    3-> va_arg() fetches the next argument from the argument list.

    4-> va_end(), which performs any necessary cleanup

    ------------------------------------------------------------------------

    ############ Callback routine #####################

    GESL confidential

  • C Interview questions 43

    A callback routine is a routine (function or procedure) in your program that Windows calls.More generally, a callback is a means of sending a function as a parameter into another function.When the callback function has completed, control is passed back to the original function.

    -----------------------------------------------In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a function defined in a higher-level layer.Usually, the higher-level code starts by calling a function within the lower-level code passing to it a pointer or handle to another function. While the lower-level function executes, it may call the passed-in function any number of times to perform some subtask. In another scenario, the lower-level function registers the passed-in function as a handler that is to be called asynchronously by the lower-level at a later time in reaction to something.

    A callback can be used as a simpler alternative to polymorphism and generic programming, in that the exact behavior of a function can be dynamically determined by passing different (yet compatible) function pointers or handles to the lower-level function. This can be a very powerful technique for code reuse.

    Callback functions separate the caller from the callee, the caller does'nt care who the callee is ----------------------------------------------------########## Reentrant code ####################

    A programming routine that can be used by multiple programs simultaneously.It is used in operating systems and other system software as well as in multithreading,where concurrent events are taking place. It is written so that none of its codeis modifiable (no values are changed) and it does not keep track of anything.The calling programs keep track of their own progress (variables, flags, etc.),thus one copy of the reentrant routine can be shared by any number of users or processes.

    Conceptually, it is as if several people were each baking a cake from a single copyof a recipe on the wall. Everyone looks at the master recipe, but keeps track of theirown progress by jotting down the step they are at on their own scratchpad so they canpick up where they left off. The master recipe is never disturbed.

    -------------------------------------------------

    GESL confidential

  • C Interview questions 44

    A computer program or routine is described as reentrant if it can be safely executedconcurrently; that is, the routine can be re-entered while it is already running.To be reentrant, a function must hold no static non-constant data, must not returnthe address to static non-constant data, must work only on the data provided to itby the caller, must not rely on locks to singleton resources, and must not callnon-reentrant functions.

    Multiple levels of 'user/object/process priority' and/or multiprocessing usuallycomplicate the control of reentrant code. Also, IO code is usually not reentrantbecause it relies on shared, singleton resources such as disks.

    -------------------------------------------In the following piece of C code, neither functions f nor g are reentrant.

    int g_var = 1;

    int f(){ g_var = g_var + 2; return g_var;}

    int g(){ return f() + 2;}

    int main(){ g(); return 0;}-----------------------------------------These slightly-altered versions are reentrant:

    int f(int i){ int priv = i; priv = priv + 2; return priv;}

    int g(int i){ int priv = i; return f(priv) + 2;}

    int main(){ g(1); return 0;}

    GESL confidential

  • C Interview questions 45

    ------------------------------------Re-entrant code is code written to safely allow more than one thread of control to access it at once. This mainly occurs in multi-threaded situations, such asin server-side code that may be shared by multiple remote users.

    To make code safely re-entrant takes a lot of care, and usually requires the use of locking techniques to prevent threads modifying local data (e.g. variables) in use by another thread, or the avoidance----------------------------------------------------A reentrant function does not hold static data over successive calls, nor does it return a pointer to static data. All data is provided by the caller of the function. A reentrant function must not call non-reentrant functions.

    The use of global data is thread-unsafe. It should be maintained per thread or encapsulated, so that its access can be serialized. Many non-reentrant functions return a pointer to static data. This can be avoided in two ways:

    Returning dynamically allocated data. In this case, it will be the caller's responsibility to free the storage. The benefit is that the interface does not need to be modified. However, backward compatibility is not ensured; existing single-threaded programs using the modified functions without changes would not free the storage, leading to memory leaks. Using caller-provided storage. This method is recommended, although the interface needs to be modified.

    -----------------------------------------------------------------------------------

    #### gcov - coverage testing tool ########

    gcov is a test coverage program. Use it in concert with GCC to analyze your programs to help create more efficient, faster running code. You can use gcov as a profiling tool to help discover where your optimiza- tion efforts will best affect your code. You can also use gcov along with the other profiling tool, gprof, to assess which parts of your code use the greatest amount of computing time.

    Profiling tools help you analyze your codes performance. Using a pro- filer such as gcov or gprof, you can find out some basic performance statistics, such as:

    how often each line of code executes

    what lines of code are actually executed

    how much computing time each section of code uses

    Once you know these things about how your code works when compiled, you can look at each module to see which modules should be optimized. gcov helps you determine where to work on optimization.

    Software developers also use coverage testing in concert with test- suites, to make sure software is actually good enough for a release.

    GESL confidential

  • C Interview questions 46

    Testsuites can verify that a program works as expected; a coverage pro- gram tests to see how much of the program is exercised by the test- suite. Developers can then determine what kinds of test cases need to be added to the testsuites to create both better testing and a better final product.

    You should compile your code without optimization if you plan to use gcov because the optimization, by combining some lines of code into one function, may not give you as much information as you need to look for hot spots where the code is using a great deal of computer time. Likewise, because gcov accumulates statistics by line (at the lowest resolution), it works best with a programming style that places only one statement on each line. If you use complicated macros that expand to loops or to other control structures, the statistics are less help- ful---they only report on the line where the macro call appears. If your complex macros behave like functions, you can replace them with inline functions to solve this problem.

    gcov creates a logfile called sourcefile.gcov which indicates how many times each line of a source file sourcefile.c has executed. You can use these logfiles along with gprof to aid in fine-tuning the perfor- mance of your programs. gprof gives timing information you can use along with the information you get from gcov.

    gcov works only on code compiled with GCC. It is not compatible with any other profiling or test coverage mechanism.

    $ gcc -fprofile-arcs -ftest-coverage tmp.c $ a.out $ gcov tmp.c 87.50% of 8 source lines executed in file tmp.c Creating tmp.c.gcov.

    $ vi tmp.c.gcov

    ------------------------------------------------------------------------

    ##### Valgrind #########

    $valgrind -v --tool=memcheck --leak-check=full --log-file=logfile.txt ./a.out

    ##### How to take patch ####

    $diff -NaurbB org_dir mod_dir > result.patch

    --------------------------------------------------------------------

    ##### Make ##############

    prog1 : file1.o file2.o file3.o CC -o prog1 file1.o file2.o file3.o

    file1.o : file1.cc mydefs.h

    GESL confidential

  • C Interview questions 47

    CC -c file1.cc

    file2.o : file2.cc mydefs.h CC -c file2.cc

    file3.o : file3.cc CC -c file3.cc

    clean : rm file1.o file2.o file3.o--------------------------------------------------------OBJS = file1.o file2.o file3.o

    prog1 : $(OBJS) CC -o prog1 $(OBJS)

    file1.o : file1.cc mydefs.h CC -c file1.cc

    file2.o : file2.cc mydefs.h CC -c file2.cc

    file3.o : file3.cc CC -c file3.cc

    clean : rm $(OBJS)------------------------------------------OBJS = file1.o file2.o file3.o

    prog1 : ${OBJS} ${CXX} -o $@ ${OBJS}

    file1.o file2.o : mydefs.h

    clean : rm ${OBJS}

    ----------------------------------------------------------make -> use the default descriptor file, build the first target in the file

    make myprog -> use the default descriptor file, build the target myprog

    make -f mymakefile -> use the file mymakefile as the descriptor file, build the first target in the file

    make -f mymakefile -> myprog use the file mymakefile as the descriptor file, build the target myprog

    -----------------------------------------------------------------LIBS = -lm OBJS = file1.o file2.o $(more_objs) more_objs = file3.o CXX = CC DEBUG_FLAG = # assign -g for debugging

    GESL confidential

  • C Interview questions 48

    prog1 : ${objs} ${CXX} $(DEBUG_FLAG) -o prog1 ${objs} ${LIBS}--------------------------------------------------------.cc.o: $(CXX) $(CXXFLAGS) -c $