“ C ” 1. What does static variable mean? Static variable : A static local variable exists for the duration of the program, but is only visible in the function body. Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. 2. What is a pointer? Pointer : A pointer is a variable used to store address of another variable or any memory location. A pointer provides a way of accessing a variable without referring to the variable directly. Syntax: datatype *pvar1,*pvar2… ; 3. What is a structure? Structure : Structures are data structures whose individual elements can differ in type. A single data structure may contain integers, floating points, pointers, arrays as well as other structures. The individual structure elements are referred to as members. Syntax: struct structure _name { data_type member1; data_type member2; ------------ --------------; ------------ --------------; } ; //Semicolon is must & Before semicolon you can declare structure 4. What are the differences between structures and arrays? Differences between structures and arrays : 1. Array elements are homogeneous. Structure elements are of different data type. 2. Array allocates static memory and uses index / subscript for accessing elements of the array. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure. 3. Array is a pointer to the first element of it. Structure is not a pointer 4. Array element access takes less time in comparison with structures.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
“ C ”
1. What does static variable mean?
Static variable :
A static local variable exists for the duration of the program, but is only visible
in the function body. Static automatic variables continue to exist even after the block in
which they are defined terminates. Thus, the value of a static variable in a function is
retained between repeated function calls to the same function.
2. What is a pointer?
Pointer :
A pointer is a variable used to store address of another variable or any memory
location. A pointer provides a way of accessing a variable without referring to the
variable directly.
Syntax: datatype *pvar1,*pvar2… ;
3. What is a structure?
Structure:
Structures are data structures whose individual elements can differ in type. A
single data structure may contain integers, floating points, pointers, arrays as well as
other structures. The individual structure elements are referred to as members.
Syntax: struct structure _name
{
data_type member1;
data_type member2;
------------ --------------;
------------ --------------;
} ; //Semicolon is must & Before semicolon you can declare structure
4. What are the differences between structures and arrays?
Differences between structures and arrays :
1. Array elements are homogeneous. Structure elements are of
different data type.
2. Array allocates static memory and uses index / subscript for
accessing elements of the array. Structures allocate dynamic
memory and uses (.) operator for accessing the member of a
structure.
3. Array is a pointer to the first element of it. Structure is not a pointer
4. Array element access takes less time in comparison with structures.
5. In header files whether functions are declared or defined?
Whether functions are declared or defined in header files :
Functions and macros are declared in header files. Header files
would be included in source files by the compiler at the time of compilation. Header files
are included in source code using #include directive.#include<some.h> includes all the
declarations present in the header file „some.h‟. A header file may contain declarations of
sub-routines, functions, macros and also variables which we may want to use in our
program. Header files help in reduction of repetitive code.
6. What are the differences between malloc() and calloc()?
Differences between malloc( ) and calloc( ) :
There are two differences. First, is in the number of arguments. Malloc()
takes a single argument (memory required in bytes), while calloc() needs two arguments
(number of variables to allocate memory, size in bytes of a single variable). Secondly,
malloc() does not initialize the memory allocated, while calloc() initializes the allocated
memory to ZERO.
7. What are macros? What are its advantages and disadvantages?
Macros :
Macros are the identifiers that represent statements or expressions. To
associate meaningful identifiers with constants, keywords, and statements or
expressions, #define directive is used.
The advantage of using macro is the execution speed of the program fragment.
When the actual code snippet is to be used, it can be substituted by the name of the
macro. The same block of statements, on the other hand, need to be repeatedly hard
coded as and when required.
The disadvantage of the macro is the size of the program. The reason is, the
pre-processor will replace all the macros in the program by its real definition prior to the
compilation process of the program.
8. Difference between pass by reference and pass by value?
Pass by references and pass by value:
Pass By Reference :
- In Pass by reference address of the variable is passed to a function. Whatever changes
made to the formal parameter will affect to the actual parameters
- Same memory location is used for both variables.(Formal and Actual)-
- it is useful when you required to return more than 1 values
Pass By Value:
- In this method value of the variable is passed. Changes made to formal will not affect
the actual parameters.
- Different memory locations will be created for both variables.
9. What is static identifier?
Static Identifier :
The static identifier is used for initializing only once, and the value retains during the life
time of the program / application. A separate memory is allocated for „static‟ variables. This
value can be used between function calls. The default value of an uninitialized static variable is
zero. A function can also be defined as a static function, which has the same scope of the static
variable.
10. Where are the auto variables stored?
Auto variable storage :
Main memory and CPU registers are the two memory locations where auto variables are
stored. Auto variables are defined under automatic storage class. They are stored in main
memory. Memory is allocated to an automatic variable when the block which contains it is called
and it is de-allocated at the completion of its block execution.
Auto variables:
Storage : main memory.
Default value : garbage value.
Scope : local to the block in which the variable is defined.
Lifetime : till the control remains within the block in which the variable is defined.
11. Where does global, static, local, register variables, free memory and C Program instructions get stored?
Local/auto variables, which is declared in stack area of memory. A variable prefixed with
register will be stored in registers. Global variables stored in uninitialized data segment
static variables stored in initialized data segment. Free memory (dynamic memory allocations)
will be stored in heap memory (i.e. in data segments). Const variables also stores in text
segments
12. Difference between arrays and linked list?
Differences between arrays and linked list :
Arrays and Linked list both are list data structures used for maintaining a
list of values. Arrays use sequential allocation while Linked list uses linked allocation.
> Linked list uses some extra memory i.e. link pointer.
> Indexing an element, e.g. accessing kth element is cheaper in arrays and costly in Linked list.
> Insertion and Deletion of elements is a cheaper operation in Linked lists.
> Since nodes in Linked list are dynamically allocated, it has no limitations on growth (apart
from memory constraints).
> Merging Lists is easier in case of Linked lists.
> Breaking a List into two or more lists is easier in case of Linked lists.so Linked list is a better
data structure in most cases. Arrays are goes mostly for static data structures.
13. What are enumerations?
Enumerations :
An enumeration consists of a set of named integer constants. An
enumeration type declaration gives the name of the (optional) enumeration tag and defines the
set of named integer identifiers (called the "enumeration set," "enumerator constants,"
"enumerators," or "members"). A variable with enumeration type stores one of the values of the
enumeration set defined by that type.
Syntax:
enum identifier opt { enumerator-list }
enum identifier
14. Describe about storage allocation and scope of global, extern, static, local and register variables?
Storage allocation and scope of global ,extern ,static ,local and register variables :
The storage allocation / class determine the memory part where the storage space
is allocated for variables, functions and how long the allocation of storage continues to exist.
The scope of a variable is specified by its storage allocation. This is specified by
the keywords – auto, extern, static and register.
- „auto‟ variables stores in the memory storage. Majority of the variables in a program
/ application are of type „auto‟. Their scope might be local or global.
- „extern‟ variables are of global variables and can be declared in another source file
which could be external / outside the current program scope,
- „register‟ variables are allocated in the CPU registers. These variables storage and
accessibility is much faster than other variables, being they are stored in CPU itself. The
variables of repeated usage or access time is critical, can be declared as register variables.
- „static‟ variables provide a lifetime over the program, and provide a way for
limiting the scope of such variables. These variables are automatically initialized to zero and
could be specified for „auto‟ and „extern‟ variables. The values are retained, even though they are
declared in local scope, between the repeated function calls to the same function.
15. What are register variables? What are the advantage of using register variables?
register variables :
The variables of „register‟ type modifier will inform the compiler for storing the
variables in a register of CPU.
The advantage of this type modifier is the access optimization and speed of program
execution. The operations of these variables are faster by orders of magnitude
16. What is the use of typedef?
typedef :
A typedef declaration is a declaration with typedef as the storage class. The declarator
becomes a new type. You can use typedef declarations to construct shorter or more meaningful
names for types already defined by C or for types that you have declared. Typedef names allow
you to encapsulate implementation details that may change.
typedef is used to define new data type names to make a program more readable to the
programmer.
17. Can we specify variable field width in a scanf() format string? If possible how?
It is possible to specify variable field width in a scanf() format string. By using %s control string.
This character reads a string of variable field width up to the first white space character.
Ex: scanf(“%s”, name); // where name is a character array
18. Out of fgets() and gets() which function is safe to use and why?
The function fgets() function is safer to use. It checks the bounds, i.e., the size of the buffer and
does not cause overflow on the stack to occur. gets() does not check the bounds.
19. Difference between strdup and strcpy?
Differences between strdup and strcpy :
The function strcpy() will not allocate the memory space to copy. A pointer to the string
to copy and a pointer to place to copy it to should be given.
The function strdup() will occupy / grab itself the memory space for copying the string to.
This memory space needs to be freed up later when it is of no use anymore.
20. What is recursion?
Recursion :
Recursive function is a function which contains a call to itself. Recursive function
allows you to divide your complex problem into identical single simple cases which can handle
easily. This is also a well-known computer programming technique: divide and conquer.
21. Differentiate between a for loop and a while loop? What are it uses?
Differences between a for loop and a while loop :
22 . What are the different storage classes in C?
Storage classes in C :
Storage class defined for a variable determines the accessibility and longevity of the
variable. The accessibility of the variable relates to the portion of the program that has
access to the variable. The longevity of the variable refers to the length of time the
variable exists within the program.
Auto Automatic variable, also called as local variable and it has scope only within the function
block where it is defined.
External
External variable are defined outside any function and memory is set aside for this type of
variable once it is declared and remained until the end of the program. These variables are
also called global variables.
Static The static automatic variables, as with local variables, are accessible only within the
function in which it is defined. Static automatic variables exist until the program ends in the
same manner as external variables. In order to maintain value between function calls, the
static variable takes its presence.
23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
equivalent pointer expression for referring the same element aijkl :
it is a[i][j][k][l]; so in pointer reference:
(*(*(*(*(a+i)+j))+k)+l)
24. What is difference between Structure and Unions?
Differences between Structures and Unions :
1. union allocates the memory equal to the maximum memory required by the
member of the union but structure allocates the memory equal to the total memory required by
the members.
2. In union, one block is used by all the member of the union but in case of structure,
each member have their own memory space.
3. union is best in the environment where memory is less as it shares the memory
allocated.But structure can not implemented in shared memory.
4. As memory is shared,ambiguity are more in union,but less in structure.
5. self referencial union can not be implemented in any datastructure ,but self
referencial structure can be implemented.
25. What the advantages of using Unions?
Advantages of using Unions :
In case of structure each variables have their own storage location whereas for
unions all the variables share a common memory location. In structure all the variables can be
handled at a time but for union only a member can be handled at a time.
26. What are the advantages of using pointers in a program?
Advantages of using Pointers in a program :
1) Function cannot return more than one value. But when the same function can modify
many pointer variables and function as if it is returning more than one variable.
2) In the case of arrays we can decide the size of th array at runtime by allocating the
necessary space.
27. What is the difference between Strings and Arrays?
Difference between Strings and Arrays :
1. String can hold only char data. Where as an array can hold any data type.
An array size cannot be changed. Where as a string size can be changed if it is a char
pointer
2. The last element of an array is an element of the specific type. The last character of a
string is a null – „\0‟ character.
3. The length of an array is to specified in [] at the time of declaration (except char []).
The length of the string is the number of characters + one (null character).
28. In a header file whether functions are declared or defined?
Refer to Question 5.
29. What is a far pointer? where we use it?
Far pointer:
A far pointer is a 32 bit pointer to an object anywhere in memory. In
order to use it, the compiler must allocate a segment register, load it with the segment portion of
the pointer, and then reference memory using the offset portion of the pointer relative to the
newly loaded segment register. This takes extra instructions and extra time, so it is the slowest
and largest method of accessing memory, but it can access memory that is larger than 64kb,
sometimes, such as when dealing with video memory, a needful thing.
A far pointer contains a 16 bit segment part and a 16 bit offset part. Still,
at any one instant of time, without "touching" segment registers, the program only has access to
four 64kb chunks, or segments of memory. If there is a 100kb object involved, code will need to
be written to consider its segmentation, even with far pointers.
30 . How will you declare an array of three function pointers where each function receives two ints and returns a float?
Declaration for an array of three function pointers where each function receives two ints
and returns a float :
float (*fn[3])(int,int)
31. what is a NULL Pointer? Whether it is same as an uninitialized pointer?
Null Pointer :
An uninitialized pointer is a pointer that has not been assigned a value; it's uninitialized.
The value of an uninitialized pointer is undefined (it could be anything).
A null pointer is simply a pointer that has a value of NULL.
A word of advice: initialize your pointers to NULL.
This allows you to see that the pointer is invalid; to check if an uninitialized pointer is
valid is quite impossible.
32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
Null Macro:
NULL Macro is simply what is defined as 0 in a macro provided by the library
Difference between Null Pointer and a Null Macro
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.
33. What does the error 'Null Pointer Assignment' mean and what causes this error?
Null Pointer Assignment Error :
A NULL pointer assignment is a runtime error It occurs due to various reasons one is that ur
program has tried to access an illegal memory location. Illegal location means either the location
is in the operating systems address space or in the other processes memory space. In stdio.h
NULL is defined as 0
So whenever your program tries to access 0th location the operating system kills your
program with runtime assignment error because the 0th location is in the operating systems
address space and operating system doesn‟t allow access to its address space by user program .
34. What is near, far and huge pointers? How many bytes are occupied by them?
Near ,Far and huge Pointers :
Near pointer: Near pointer is 16 bit wide and holds only offset address. This can
point up to 64kb or 0xFFFF offset in a given segment.
int i = 0;
int * i_pointer = &i;
Far pointer: Far pointers are 32 bit wide. It holds both 16bit segment and 16bit
offset address. Thus a far pointer can point any segment and any offset inside that segment.
MK_FP is a compiler macro which takes segment and offset value and constructs a far pointer.
int far * i_pointer = (int far * )MK_FP(0xA000, 0);
i_pointer can have offset from 0 to 0xFFFF.
Thus it can access address range 0xA0000 to 0xAFFFF
Huge pointer: Huge pointers are also far pointers i.e. 32 bit pointer. The difference
is compiler rounds of the offset to zero of a far pointer when offset reaches to 0xFFFF but for
huge pointer it increments the segment thus huge pointer can be increased or decreased
uniformly between any segments and thus can have any value from 0 to 1MB.
43. How can we read/write Structures from/to data files?
Read/Write Structures from/to data files :
There 2 function given in C++. They are fread() & fwrite(). Using them we can read & write
structures
from/to data files respectively.
Basic representation:
fread(&structure, sizeof structure,1,fp);
fread function recieves a pointer to structure and reads the image(memory) of the
structure as a stream of bytes. Sizeof gives the bytes which was occupied by structure.
fwrite(&structure, sizeof structure,1,fp);
fwrite function recieves a pointer to structure and writes the image(memory) of the
structure as a stream of bytes. Sizeof gives the bytes which was occupied by structure.
44. What is the difference between an enumeration and a set of pre-processor # defines? Difference between an enumeration and a set of pre-processor # defines :
It is always better to use enums over #define for this kind of cases. One thing is type safety.
Another one is that when you have a sequence of values you only have to give the beginning of
the sequence in the enum, the other values get consecutive values.
enum {
ONE = 1,
TWO,
THREE,
FOUR
};
instead of
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
As a side-note, there is still some cases where you may have to use #define (typically for some
kind of macros, if you need to be able to construct an identifier that contains the constant), but
that's kind of macro black magic, and very very rare to be the way to go. If you go to these
extremities you probably should use a C++ template (but if you're stuck with C...).
45. What do the 'c' and 'v' in argc and argv stand for?
In argc c for argument count and in argv v for argument vector .
In C, we can supply arguments to ‟main‟ function. The arguments that we pass to main ( ) at
command prompt are called command line arguments. These arguments are supplied at the
time of invoking the program.The main ( ) function can take arguments as:
main(int argc, char *argv[]) { }
The first argument argc is known as ‟argument counter‟. It represents the number of
arguments in the command line. The second argument argv is known as ‟argument vector‟. It is
an array of char type pointers that points to the command line arguments. Size of this array will
be equal to the value of argc.
46. Are the variables argc and argv are local to main?
The variables argc and argv are local to main
Reason :
Yes why because these variables written in main function only not outside main. These
belong to main block but not to other. So according to my knowledge these command line
arguments are local to main.
47. What is the maximum combined length of command line arguments including the space between adjacent arguments?
The maximum combined length of command line arguments including the space between
adjacent arguments :
Presumably this would be (INT_MAX-1) * SIZE_MAX. That is each argument can presumably
be up to SIZE_MAX chars and there can be INT_MAX - 1 arguments (one being needed for
argv[0] the program name).
Since the actual values of INT_MAX and SIZE_MAX are implementation defined no maximum
can be definitively given ahead of time.
That said one might suspect the hosting OS and/or startup code would provide somewhat more
stringent limits.
48. 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
49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
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.
(Or)
Trap the arguments in variables which can be passed to other function.
50. What are bit fields? What is the use of bit fields in a Structure declaration?
Bit fields and its usuage in structure declaration :
When the storage is at premium it may be necessary to pack several objects into single machine
word one common use is a set of single bit flags in application like compiler symbol tables. A bit
field or field for short is a set of adjacent bits with a single implementation - defined storage unit.
struct {
unsugned int is_keyword : 1;
unsigned is_extern :1;
unsigned is_static : 1 ;
} flags ;
flags.is_extern = flags.is_static = 1 ; to tun this bit on.
51 . To which numbering system can the binary number 1101100100111100 be easily converted to?
1101100100111100 conversion
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
52. Which bit wise operator is suitable for checking whether a particular bit is on or off?
Checking whether a particulat bit is on or off :
Its Bitwise AND (&)
for Ex
I need to check if 3rd bit from right(Starting from 0th) is ON in a variable x or OFF.
then see this code:
int x=24;
int tester=1;
tester = tester << 3; \Makes tester as 00001000
if((x&tester)!=1)
printf("3rd bit from left in x is ON");
else
printf("3rd bit from left in x is OFF");
Explaination:
x = 24 i.e. 0001 1000
tester = 1 i.e. 0000 0001
tester = tester << 3 does:
tester = 8 i.e. 0000 1000
now x&tester i.e.
0001 1000
&&&&&&&&
0000 1000
-------------
0000 1000
which is NON ZERO hence decides that 3rd bit is SET / ON.
if x = 5 (0000 0101)
then x&tester i.e.
00000101 &
00001000
------------
00000000
which is ZERO hence decides that 3rd bit is UNSET / OFF.
In Brief: Bitwise AND is used to CHECK / TEST a particular bit.
Bitwise OR is used to SET (Make it 1) a particular bit.
Bitwise XOR is used to TOGGLE (1to0 or 0to1) a particular bit.
Bitwise AND is also used to RESET a particular bit (if ANDed with 11110111 say I have to
reset 4th bit).
53. Which bit wise operator is suitable for turning off a particular bit in a number?
the bit wise AND operator.
In the following code snippet, the bit number 24 is reset to zero.
some_int = some_int & ~KBit24;
54. Which bit wise operator is suitable for putting on a particular bit in a number?
Shift to the position first and use XOR (^) to switch the bit on/off. AND (&) to check if it's on
or off. In both cases the 2nd operand will be 1. (Ex. int switch = x ^ 1; int check = x & 1; This
is only if you are checking for the least significant bit, the furthest one to the right.)
55. Which bit wise operator is suitable for checking whether a particular bit is on or off?
Kindly refer to Q.52
56. which one is equivalent to multiplying by 2:Left shifting a number by 1 or Left shifting an
unsigned int or char by 1?
left shifting by 1 it is multiplying by 2
right shifting by 1 it is dividing by 2
57. Write a program to compare two strings without using the strcmp() function.
program to compare two strings without using the strcmp() function :
#include <stdio.h>
#include <conio.h>
main()
{
//please read two strings int str1 and str2//
while(str1[i]!='/0' &&str2[i]!='/0')
if(str1[i]!=str2[i])
flag=1;
if(flag==1)
printf("equal");
}
#include
main()
{
//please read two strings int str1 and str2//
while(str1[i]!='/0' &&str2[i]!='/0')
if(str1[i]!=str2[i])
flag=1;
if(flag==1)
printf("equal");
}
58. Write a program to concatenate two strings. program to concatenate two strings :
#include<stdio.h>
#include<conio.h>
main()
{
char s1[20],s2[20];
printf("enter first string");
scanf("%s",s1);
printf("enter second string");
scanf("%s",s2);
string_concatenate(&s1,&s2);
}
count_characters(char *x)
{
int i=0, count=0;
for(i=0;*(x+i)!='\0';i++)
count++;
return count;
}
string_concatenate(char *s1,char *s2)
{
int i,j;
char s3[50];
for(i=0;i
s3[i]=s1[i];
for(j=0;j
s3[i+j]=s2[j];
s3[i+j]=s2[j];
printf("%s",s3);
getch();
}
59. Write a program to interchange 2 variables without using the third one.
Interchanging 2 variables without using the third one :
#include<stdio.h>
#include<conio.h>
void main
{
int a,b;
printf("enter the two no");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("a=%d,b=%d",a,b);
getch();
}
60. Write programs for String Reversal & Palindrome check