Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Tuesday, June 6, 2017

C program that prints itself.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *fp;
    if ((fp = fopen(__FILE__, "r")) == NULL)
    {
        printf("Error! opening file %s\n", __FILE__);
        exit(1);
    }
    while(!feof(fp))
    {
        printf("%c", fgetc(fp));
    }
    fclose(fp);

    getch();   
    return 0;
}

Wednesday, May 31, 2017

What is the difference between 'global' and 'static global' in C?

All static variables, no matter where they are allocated, as well as all global variables, are subjected to "static initialization". They must be initialized by the program before it starts. If you haven't initialized them explicitly, they are implicitly initialized to zero (or NULL for pointers).

Wednesday, February 27, 2013

Explain the meaning of "Segmentation Violation".

At the time of compiling the program, a segmentation violation usually indicates an attempt to access memory which doesn't even exist.

What is the advantage of 'do-while' loop as compared to 'while' loop?

A while loop checks the condition first before executing the content whereas do-while loop executes the content of the loop before checking the condition and makes obligatory to enter the loop at least once.

What is the size of register for storage class?

register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the size of a processor's general-purpose registers (GPRs) and the default size is usually one word or 2 byte or 16 bits.

What are Bit-fields?

The variables defined with a fixed width are called bit fields. A well-known usage of bit-fields is to represent a set of bits, and/or series of bits. They are space-saving structure members. They allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. The default integer type for a bit field is unsigned.

The declaration of a bit-field inside a structure has the form:

struct
{
  type [member_name] : width ;
};

What is a self-referential structure?

A structure containing a reference to itself as a member is known as Self-Referential Structure.

struct linked_list_node
{
int data;
struct linked_list_node *next;  // self reference
};

What do you mean by associativity and precedence?

Precedence denotes the order or priority of evaluation whereas associativity implies the direction of evaluation.

What are dangling, wild, void, and null pointers?


A pointer pointing to a memory location which is deleted or freed is known as Dangling Pointer.

A pointer which has not necessarily initialized prior to its usage is a Wild Pointer.

A pointer pointing to nothing or that does not refer to a valid memory location is a NULL Pointer.

The pointer not having any type associated with it and can hold the address of any type is known as Void Pointer (aka Generic Pointer).

Are functions declared or defined in header files?

Traditionally the standard functions are declared in header files and defined in the library routines only.

What is the difference between '#include' and '#include "File"'?


It is compiler dependent. Generallly '#include "File"' prioritizes headers to be checked in the current working directory over system headers. And if there is not a suitable match, it moves on to check the system paths. "#include <File>" always looks out for system headers.

How could you find the size of a variable with out using sizeof operator?


#include <stdio.h>

#define SIZEOF(var)  ((size_t)(&(var)+1) - (size_t)(&(var)))

main( )
{
int x;
printf ("The size of x is %d\n", SIZEOF(x) );
}

Monday, February 25, 2013

How could you multiply 2 Integers using bit-wise operators?


#include<stdio.h>

main()
{
int a, b, num1, num2, result=0;  
printf("\nEnter the numbers to be multiplied :");
scanf("%d%d",&num1,&num2);
a=num1;
b=num2;
while(num2 != 0)            
{
if (num2 & 01)              
               {
        result+=num1;  
               }
num1<<=1;                
                num2>>=1;                
}
printf("\nMultiplication of %d*%d=%d", a, b, result);
}

What is the difference between '#define' and 'typedef'?


(a) typedef keep the property of attributes whereas #define doesn’t. For example

typedef char *type_t;
#define char *type_d

type_t s1,s2;
type_d s3,s4;

In the above declarations, s1,s2 and s3 are all declared as char* but s4 is declared as a char, which is probably not the intention.

(b) #define keeps string attributes whereas typedef doesn’t.

#define int INT;
typedef int MYINT

unsigned MYINT a;
unsigned INT a; /* Illegal */

For the typedef scenario, it doesn't change to unsigned 'int a' but in #define case it works!!!.

Tuesday, July 31, 2012

How do you flip bits on and off?

Use xor to flip between 1 and 0.  
x = x ^ 1;   // or x ^= 1;
This will change x alternately between 0 and 1.

How do you divide a number by 2 without division?

Just right shift the number by 1.
main()
{
    int x=6;
    printf("%d\n", y>>1); /* Divide by 2 */
    printf("%d\n", y>>2); /* Divide by 4 */
}

Output:
3
1

How do you multiply a number by 2 without multiplication?

Just shift left the number by 1.
main()
{
    int x=6;
    printf("%d\n", x<<1); /* Multiply by 2 */
    printf("%d\n", x<<2); /* Multiply by 4 */
}

Output:
12
24

Friday, October 21, 2011

Implement semaphore in C.

#include <stdio.h>
#include <pthread.h>

void* thread_a( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp = fopen ("thread_a.txt", "w+");
    fprintf(fp,"%s","thread_a");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_b( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_b.txt", "w+");
    fprintf(fp,"%s","thread_b");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

void* thread_c( void* data )
{
    pthread_mutex_t* pmtx = (pthread_mutex_t*)data;
    pthread_mutex_lock( pmtx );
    FILE *fp;
    fp= fopen ("thread_c.txt", "w+");
    fprintf(fp,"%s","thread_c");
    fclose(fp);
    pthread_mutex_unlock( pmtx );
    return NULL;
}

int main()
{
    pthread_mutex_t mtx;
    pthread_t tA;
    pthread_t tB;
    pthread_t tC;
    pthread_mutex_init( &mtx, NULL );
    pthread_create( &tA, NULL, &thread_a, &mtx );
    pthread_join( tA, NULL );  /* wait for the thread_a to finish */
    pthread_create( &tB, NULL, &thread_b, &mtx );
    pthread_join( tB, NULL );  /* wait for the thread_b to finish */
    pthread_create( &tC, NULL, &thread_c, &mtx );
    pthread_join( tC, NULL );  /* wait for the thread_c to finish */
   
    return 0;
}

Friday, October 7, 2011

What is the difference between process and thread?

Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space while processes run in separate memory spaces.

All the threads running within a process share the same address space, file descriptor, stack and other process related attributes. onthe other hand, each process has thier own virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution.

What is the difference between static and shared library?

In Unix, Static library has an extension of ".a" which is equivalent to ".lib" in Windows. on the contrary, dynamic or shared library has got ".so" as extension equivqlent to ".dll" in Windows.

Static libraries increase the size of the code in the binary. It is directly linked into the program at compile time. A program using a static library takes copies of the code from the static library and makes it part of the program. They're always loaded with the currently compiled version of the code. As the code is connected at compile time there are not any additional run-time loading costs.

Dynamic libraries are stored and versioned separately. Dynamic libraries aren't necessarily loaded; they are usually loaded when first called and can be shared among components that use the same library (multiple data loads, one code load). It allows you to replace the shared object with one that is functionally equivalent, but may have added performance advantages without needing to recompile the program that makes use of it.Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.