Sunday 11 December 2011

Sherlock Holmes

Hello friends, I have a collection of 59 story books of Sherlock Holmes. I share these books below :

Full Episode! Mirakkel-9, Episode-17, Part-2

Full Episode! Mirakkel-9, Episode-17, Part-2

Posted by MIRAKKEL - AKKEL CHALLENGER on Thursday, January 14, 2016

Saturday 1 October 2011

C Ques & Ans page 3


How can you increase the size of a dynamically allocated array ?
/* Allocate space for an array with ten elements of type int. */ 
int *ptr = malloc(10 * sizeof (int)); 
if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc
It is often useful to be able to grow or shrink a block of memory. This can be done usingrealloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is 
void *realloc(void *pointer, size_t size);
When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically ?
As for pointers, I think you have to readjust them. Pointers are just variables that store a memory address in them. You can have as many pointers that points to a single location in memory as you want.
Which function should be used to free the memory allocated by calloc() ?
free() is a function used to free the memory allocated dynamically ,by both malloc and calloc functions.
free(ptr): ptr is a pointer to a memory block which has already been creeated by malloc or calloc.
How much maximum can you allocate in a single call to malloc() ?
Theoretically, as many bytes whose total number can be expressed with type 'size_t'. But the range of 'size_t' is implementation defined. It must be an unsigned integer type, with a minimum magnitude of 65535. The maximum single allocation size possible is also limited by the host operating system.
Can you dynamically allocate arrays in expanded memory ?
int *ptr = malloc(10 * sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);
What is object file ? How can you access object file ?
An object file is binary representation of source(text) file. On Linux, object and executable files have ELF format. It's a collection of various sections segragating type of data in:
- text section
- data section
- stack
- heap
Also addresses in an object file are relative and hence object files can't be run unless it's linked. for ex, if you make a call to printf(), object file will have an entry as
("call printf ___") where the blank is the address of printf function. Since printf is part of libc.so, you have no knowledge of its address. Linking with libc pads the correct address and enables you to call it successfully.
Which header file should you include if you are to develop a function which can accept variable number of arguments ?
stdarg.h
Read the manual for your compiler the header files for each compiler are different. 
None of the compilers I currently use have a header file called "stdarg.h" but do have "varargs.h"
Can you write a function similar to printf() ?
puts()
How can a called function determine the number of arguments that have been passed to it ?
Use the variable length argument - va_arg , va_list , ca_start and va_end macros
How do you declare the following:  
a.  An array of three pointers to chars 
b.  An array of three char pointers  
c.  A pointer to array of three chars  
d.  A pointer to function which receives an int pointer and returns a float pointer  
e.  A pointer to a function which receives nothing and returns nothings  
(a) char *ptr[3]
(b) char *array[3]
(c) char (*ptr)[3]
(d) float *(*ptr)(int*)
(e) void (*ptr)()
What do the functions atoi(), itoa() and gcvt() do ?
atoi() is a macro that converts integer to character.
itoa() It converts an integer to string
gcvt() It converts a floating point number to string.
Does there exist any other function which can be used to convert an integer or a float to a string ?
#include char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer.
value:
Is the integer to be converted to string representation.
string:
Points to the buffer that is to hold resulting string. The resulting string may be as long as seventeen bytes.
radix:
Is the base of the number; must be in the range 2 - 36.
A portable solution exists. One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10.20;
sprintf ( s, “%d %f\n”, i, f );
How would you use qsort() function to sort an array of structures ?
include stdlib.h library.
Representation: basic reoresentaion of qsort() function is,
void qsort(void *Base, size noe , size width, int (*compar)(constt void *, constt void *));
where:
Base-> Pointer indicates beginning of array.
noe-> Number of Elements.
Width-> Size of Element.
Compare-> Does comparison and returns +ve or -ve integer.It is a callback function (pointer to function).
Example:
This Examples uses structs_sort() function.It is use to compare struct_cmp_product_price() and
struct_cmp_product() as compar callbacks.struct_array is used to print structure of array.
void structs_sort(void)
{
struct st_eq structs[] = {{"Computer",24000.0f}, {"Laptop", 40000.0f},
{"Inverter", 10000.0f}, {"A.C.", 20000.0f},
{"Refrigerator", 7000.0f}, {"Mobile", 15000.0f }};
size structs_len = sizeof(structs) / sizeof(struct st_eq);
puts("*** Struct sorting (price)...");
/* original struct array */
print_struct_array(structs, structs_len);
/* sort array using qsort functions */
qsort(structs, structs_len, sizeof(struct st_ex), struct_cmp_product_price);
/* print sorted struct array */
print_struct_array(structs, structs_len);
puts("*** Struct sorting (product)...");
/* resort using other comparision function */
qsort(structs, structs_len, sizeof(struct st_eq), struct_cmp_product);
/* print sorted struct array */
print_struct_array(structs, structs_len);
}
/* MAIN program */
int main()
{
/* run all example functions */
sort_integers();
sort_cstrings();
sort_structs();
return 0;
}
How would you use bsearch() function to search a name stored in array of pointers to string ?
bsearch, It is a library function.Using this we done data entry in array. Ther is mandatry in binary search you must sorted in ascending order.And do compare two datas.For using this function we have to include stdlib.h library function.
Syntax:
void *bsearch(void *key, void *base, size num, size width);
int (*cmp)(void *emt1, void *emt2));
where;
emt->Element.
Some steps that we have to follow when we using
bsearch.
1. It is passed pointers to two data items
2. It returns a type int as follows:
2.1) <0 Element 1 is less than element 2.
2.2) 0 Element 1 is equal to element 2.
2.3) > 0 Element 1 is greater than element 2.
example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABSIZE 1000
struct node { /* These are stored in the table. */
char *string;
int length;
};
struct node table[TABSIZE];/*Table to be search*/
.
.
.
{
struct node *node_ptr, node;
/* Routine to compare 2 nodes. */
int node_compare(const void *, const void *);
char str_space[20]; /* Space to read string into. */
.
.
.
node.string = str_space;
while (scanf("%s", node.string) != EOF) 
{
node_ptr = (struct node *)bsearch((void *)(&node),(void *)table, TABSIZE,sizeof(struct node),node_compare);
if (node_ptr != NULL)
{
(void)printf("string = %20s, length = %d\n",
node_ptr->string, node_ptr->length);
}
else
{
(void)printf("not found: %s\n", node.string);
}
}}
/*
This routine compare two nodes based on an
alphabetical ordering of the string field.
*/
int node_compare(const void *node1, const void *node2)
{
return strcoll(((const struct node *)node1)->string,((const struct node *)node2)->string);
}
How would you use the functions sin(), pow(), sqrt() ?
before using these functions <math.h>
should be included in the program

sin(d) will returns the sine of d,
pow(a,b) will returns a the value a to the power b(a^b)
eg:pow(2,3) will returns 8;
sqrt(a) returns the square root of a
eg: sqrt(4) returns 2;
How would you use the functions memcpy(), memset(), memmove() ?
memcpy() function copies n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
memmove() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n bytes from the object pointed to by s2 are first copied into a temporary array of n bytes that does not overlap the objects pointed to by s1 and s2, and then the n bytes from the temporary array are copied into the object pointed to by s1.
memset() function copies c (converted to an unsigned char) into each of the first n bytes of the object pointed to by s. SYNTAX:
void *memcpy(void *s1, const void *s2, size_t n);
void *memmove(void *s1, const void *s2, size_t n);
void *memset(void *s, int c, size_t n);
How would you use the functions fseek(), freed(), fwrite() and ftell() ?
fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.
fread(s,i1,i2,f) Enter i2 dataitems,each of size i1 bytes,from file f to string s.
fwrite(s,i1,i2,f) send i2 data items,each of size i1 bytes from string s to file f.
ftell(f) Return the current pointer position within file f.
The data type returned for functions fread,fseek and fwrite is int and ftell is long int.
How would you obtain the current time and difference between two times ?
By using in built gettime() and difftime().
How would you use the functions randomize() and random() ?
Randomize() initiates random number generation with a random value.
Random() generates random number between 0 and n-1;
How would you implement a substr() function that extracts a sub string from a given string ?
substr(string, position [, count])
It extract substring starting from start and going for count characters. If count is not specified, the string is clipped from the start till the end.
What is the difference between the functions rand(), random(), srand() and randomize() ?
RAND: Rand uses a multiplicative congruential random number generator with period232 to return successive pseudo-random numbers in the range 0 to RAND_MAX.
Return Value: Rand returns the generated pseudo-random number.
RANDOM(): Random returns a random number between 0 and (num-1).random(num) is a macro defined in STDLIB.H.
RANDOMIZE(): Randomize initializes the random number generator with a random value. Because randomize is implemented as a macro that calls the time function prototyped in TIME.H, you should include TIME.H when you use this routine
SRAND(): The random number generator is reinitialized by calling srand with an argument value of 1.The generator can be set to a new starting point by calling srand with a given seed number.
What is the difference between the functions memmove() and memcpy() ?
The arguments of memmove() can overlap in memory. The arguments of memcpy() cannot.
Can you use the function fprintf() to the output on the screen ?
#include<stdio.h>
int main()
{
char name[10]="prachee";
fprintf( stdout, "Hello %s ", name );
getchar();
return 0;
}


Go to page  1 , 2 , 3  

C Ques & Ans page 2


What is a far pointer ? Where we use it ?
In large data model (compact, large, huge) the address B0008000 is acceptable because in these model all pointers to data are 32bits long. If we use small data model(tiny, small, medium) the above address won’t work since in these model each pointer is 16bits long. If we are working in a small data model and want to access the address B0008000 then we use far pointer. Far pointer is always treated as a 32bit pointer and contains a segment address and offset address both of 16bits each. Thus the address is represented using segment : offset format B000h:8000h. For any given memory address there are many possible far address segment : offset pair. The segment register contains the address where the segment begins and offset register contains the offset of data/code from where segment begins.
What is a NULL Pointer ? Whether it is same as an uninitialized pointer ?
Null pointer is a pointer which points to nothing but uninitialized pointer may point to anywhere.
What is a NULL Macro ? What is the difference between a NULL Pointer and a NULL Macro ?
There are times when it?s necessary to have a pointer that doesn?t point to anything. The macro NULL, defined in , has a value that?s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*.
The null pointer is used in three ways :
1) To stop indirection in a recursive data structure.
2) As an error value.
3) As a sentinel value.
Both are very different.
NULL macro is
#define NULL 0
it means the macro NULL will be replaced by 0 while preprocessing
But the NULL pointer means it points to nowhere i.e. contains 0. 
It contains 0 means it may be dangerous to use such pointer without assigning proper address to it otherwise NULL pointer may try to access reset address may cause the program to crash.
What does the error 'Null Pointer Assignment' mean and what causes this error ?
As null pointer points to nothing so accessing a uninitialized pointer or invalid location may cause an error.
What is near, far and huge pointers ? How many bytes are occupied by them?
far pointer is a pointer which includes a segment selector, making it possible to point to addresses outside of the current segment. Far pointers have a size of 4 bytes. They store both the segment and the offset of the address the pointer is referencing. A far pointer has an address range of 0 - 1M bytes. A far pointer can be incremented and decremented using arithmetic operators. When a far pointer is incremented or decremented ONLY the offset of the pointer is actually incremented or decremented. The segment is never incremented by the arithmetic operators. 

Near pointers have a size of 2 bytes. They only store the offset of the address the pointer is referencing. An address consisting of only an offset has a range of 0 - 64K bytes. A near pointer can be incremented and decremented using arithmetic operators (+, -, ++, and --) through the entire address range. Any attempt to increment a near pointer that has a value of 64K (0xffff) will result in a value of 0.

HUGE pointers have a size of 4 bytes. They store both the segment and the offset of the address the pointer is referencing. A huge pointer has an address range of 0 - 1M bytes. A huge pointer can be incremented and decremented using arithmetic operators. The only difference between a far pointer and a huge pointer is that a huge pointer is normalized by the compiler. A normalized pointer is one that has as much of the address as possible in the segment, meaning that the offset is never larger than 15. A huge pointer is normalized only when pointer arithmetic is performed on it. It is not normalized when an assignment is made.
How would you obtain segment and offset addresses from a far address of a memory location ?
Pointers to far objects are stored using four bytes (32 bits). The bytes are stored little endian or low to high order. The first word contains the 14-bit memory offset (bits 14 and 15 are always 0). The second word contains the page number (or segment number for function pointers). The memory address is calculated as follows:
Variable Address (Page * 0x4000L) + Offset
Function Address (Segment * 0x10000L) + Offset
Are the expressions arr and &arr same for an array of integers ?
No arr refers to address of array &arr refers address of address of array but compiler treats arr and & arr, so even you place arr and & arr no error only warnings will be displayed.
Does mentioning the array name gives the base address in all the contexts?
Mentioning the array name in C or C++ gives the base address in all contexts except one.
Syntactically, the compiler treats the array name as a pointer to the first element. You can reference elements using array syntax, a[n], or using pointer syntax, *(a+n), and you can even mix the usages within an expression. When you pass an array name as a function argument, you are passing the "value of the pointer", which means that you are implicitly passing the array by reference, even though all parameters in functions are "call by value".
There is, however, one very important distinction. While an array name is referentially the same as a pointer, it is not a pointer in that it does not occupy program referential space in the process. This means that, while you can change the value of a pointer, and thus the address to which it points, you cannot change the value of an array name. This distinction is what we call R-Value (array or pointer) as opposed to L-Value (pointer only), i.e. can the object appear on the left sign of an assignment operator.
Explain one method to process an entire string as one unit ?
By using gets() function we can do so.
What is the similarity between a Structure, Union and enumeration?
All of them let the programmer to define new data type.
Can a Structure contain a Pointer to itself ?
Yes such structures are called self-referential structures.
How can we check whether the contents of two structure variables are same or not ?
The two structure variables need to be of same type.
we can check the equality of two structure variables by comparing them individually.
example::
#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[20];
float tot;
}a,b;
void main()
{
clrscr();
printf("enter rno,total of student 1"); 
scanf("%d%f",a.rno,a.total);
printf("enter the name of student1");
scanf("%s",a.name);
printf("enter the rno and total of student2");
scanf("%d%f",b.rno,b.total);
printf("enter the name of student2");
scanf("%s",b.name);

if((a.rno==b.rno)&&(a.name==b.name)&&(a.total==b.total))
printf("two structure variables are equal");
else
printf("two structure variables are not equal");
getch();
}
How are Structure passing and returning implemented by the complier ?
When structures are passed as argument to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmer often prefer to pass pointers to structure instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supported ‘hidden’ argument to the function.
How can we read/write Structures from/to data files ?
To write out a structure we can use fwrite() as Fwrite( &e, sizeof(e),1,fp);Where e is a structure variable. A corresponding fread() invocation can read the structure back from file. calling fwrite() it writes out sizeof(e) bytes from the address &e. Data files written as memory images with fwrite(),however ,will not be portable, particularly if they contain floating point fields or Pointers. This is because memory layout of structures is machine and compiler dependent. Therefore, structures written as memory images cannot necessarily be read back by programs running on other machine, and this is the important concern if the data files you’re writing will ever be interchanged between machines.
What is the difference between an enumeration and a set of pre-processor # defines ?
Enumeration provide convenient way to associate constant values with names , an alternative to #define with advantage that the values can be generated for you. Although variables of enum types may be declared , compilers need not check that what you store in such variable is a calid value for enum. Neverthless enum variables offer a chance of checking and so are often better that #defines. In addition debugger may be able to print values of enum variables in their symbolic forms.
What do the 'c' and 'v' in argc and argv stand for?
The c in argc(argument count) stands for the number of command line argument the program is invoked with and v in argv(argument vector) is a pointer to an array of character string that contain the arguments.
Are the variables argc and argv are local to main ?
Yes both argc and argv are local to main method.Any thing you write within the parenthesis is local to the function.
What is the maximum combined length of command line arguments including the space between adjacent arguments ?
It depends on the operating system.
If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision ? If yes, which ?
Yes you have to compile a program like tcc myprog wildargs.obj
Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function ?
Using the predefined variables _argc, _argv. This is a compiler dependent feature. It works in TC/TC++ but not in gcc and visual studio.
You can copy them into global variables in the main() function, then have your other functions access those global variables. Global variables should generally be avoided, however.
What are bit fields? What is the use of bit fields in a Structure declaration ?
A bit field is a set of adjacent bits within a single implementation based storage unit that we
will call a “word”.
The syntax of field definition and access is based on structure.
Struct {
unsigned int k :1;
unsigned int l :1;
unsigned int m :1;
}flags;
the number following the colon represents the field width in bits.Flag is a variable that contains three bit fields.
To which numbering system can the binary number 1101100100111100 be easily converted to ?
Since this is a 16 bit number,
we can group these bits into 4bits a group each as
(1101)(1001)(0011)(1100)
Hence the given set of bits can be converted to HEXA DECIMAL SYSTEM as
(D93C)
16
Which bit wise operator is suitable for checking whether a particular bit is on or off ?
The bitwise AND operator. Here is an example: 

enum {
KBit0 = 1, 
KBit1,
?
KBit31,
};

if ( some_int & KBit24 )
printf ( ?Bit number 24 is ON
? );
else
printf ( ?Bit number 24 is OFF
? );
Which bit wise operator is suitable for turning off a particular bit in a number ?
The bitwise AND operator, again. In the following code snippet, the bit number 24 is reset to zero.
some_int = some_int & ~KBit24;
Which bitwise operator is suitable for putting on a particular bit in a number?
Enumeration can be done at the place where we need to assaign integer values for words,
Pre-processor dir can be used at the places where we want to give any other names to represent the original word or statement.
Enumeration provide convenient way to associate constant values with names , an alternative to #define with advantage that the values can be generated for you. Although variables of enum types may be declared , compilers need not check that what you store in such variable is a calid value for enum. Neverthless enum variables offer a chance of checking and so are often better that #defines. In addition debugger may be able to print values of enum variables in their symbolic forms.
Enums are compile time substituted constants whereas #defines are preprocessing substituted time constants.
Write a program to compare two strings without using the strcmp() function.
strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.
Syntax:
int strcmp (const char *s1, const char *s2);
Program: to compare two strings.
#include<stdio.h>
#include<string.h>
int cmpstr(char s1[10], char s2[10]);

int main()
{
char arr1[10] = "Nodalo";
char arr2[10] = "nodalo";
printf(" %d", cmpstr(arr1, arr2));
//cmpstr() is equivalent of strcmp()
return 0;
}

//s1, s2 are strings to be compared
int cmpstr(char s1[10], char s2[10]) 
{
//strlen function returns the length of argument string passed
int i = strlen(s1);
int k = strlen(s2);
int bigger;

if (i < k)
{
bigger = k;
}
else if (i > k) 
{
bigger = i;
}
else 
{
bigger = i;
}

//loops 'bigger' times
for (i = 0; i < bigger; i++) 
{
//if ascii values of characters s1[i], s2[i] are equal do nothing
if (s1[i] == s2[i])
{
}
//else return the ascii difference
else 
{
return (s1[i] - s2[i]);
}
}
//return 0 when both strings are same
//This statement is executed only when both strings are equal
return (0);
}
Write a program to interchange 2 variables without using the third one.
a ^= b; ie a=a^b
b ^= a; ie b=b^a;
a ^= b ie a=a^b;
here the numbers are converted into binary and then xor operation is performed.
You know, you’re just asking “have you seen this overly clever trick that’s not worth applying on
modern architectures and only really applies to integer variables?
Write programs for String Reversal & Palindrome check
Palindrome is a string, which when read in both forward and backward way is same.
Example: radar, madam, pop, lol, etc.
Program:
#include <stdio.h>
#include <string.h>
int main() 
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1])
{
flag = 1;
break;
}
}
if (flag)
{
printf("%s is not a palindrome\n", string1);
}
else
{
printf("%s is a palindrome\n", string1);
}
return 0;
}

Output:
Enter a string: radar
“radar” is a palindrome
Write a program to find the Factorial of a number
#include <stdio.h>
#include <conio.h>
int fact (int);
void main()
{
int n,f;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n The factorial is:%d",f);
getch();
}

int fact (int n)
{
int f=0;
if(n==0)
return (1);
else
f=n*fact(n-1);
return (f);
}
What are the advantages of using typedef in a program ?
1. Readability. Just like naming your variables properly can show how you intend to use the variable, renaming the type can help show how you intend to use all variables of this type. It eliminates the possible bug of incorrect argument ordering (e.g. if a method signature has multiple boolean flags). 
2. Portability. On different systems you might want to have the same variable name (because you're using it the same way) to be of a different type. So you keep the typedef in a header file controlled by conditional compilation (for example) for maximal portability.
3. decreases complexity for declaring complex and repeated declarations like typedef unsigned long int UINT64;
How would you dynamically allocate a one-dimensional and two-dimensional array of integers ?
/* Allocate space for an array with ten elements of type int. */ 
int *ptr = malloc(10 * sizeof (int)); 
if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc
It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);


Go to page  1 , 2 , 3  

Sherlock Holmes

Sherlock Holmes : Sherlock Holmes Sherlock Holmes : Sherlock Holmes Sherlock Holmes Stories : Sherlock Holmes Stories ...