Upload
sharathmb
View
238
Download
0
Embed Size (px)
Citation preview
8/3/2019 Renesas C Questions
1/28
Renesas C Questions
Answer the following questions to the point with examples. (Use a Word document)
1. What are macros? What are the advantages and disadvantages?
a. Macro is a piece of code written with a label. When the label is called theentire code under the name is executed. The block of code is communicated tothe compiler before entering into the main () function because it behaves as a
preprocessor directive.
b. Adv: *It helps in inline substitution of code repeatedly. *It does not involvefunction overhead.
c. Dis:*It limits the length of the code to small sizes
2. Difference between pass by reference and pass by value?
a. *Passing by reference refers to a method of passing the address of anargument in the calling function to a corresponding parameter in the calledfunction using pointers. * T he value of the argument in the callingfunction can be modified by the called function.
b. In pass-by- value , the compiler copies the value of an argument in a callingfunction to a corresponding non-pointer parameter in the called functiondefinition. *The changes in the called function will not be reflected in thecalling function.
3. What is static identifier?
a. The static identifier is used for initializing only once (with a default value of 0), and the value retains during the life time of the program / application. Aseparate memory is allocated for static variables. This value can be used
between function calls.
4. What is extern identifier?
a. The extern keyword declares a variable or function and specifies that it hasexternal linkage (its name is visible from files other than the one in which it'sdefined). It is allocated when the program begins and deallocated when the
program ends
5. What are the different storage classes in C? Explain each in detail.
a. Storage classes ' are used to define the scope (visability) and lifetime of variables and/or functions.
b. auto - storage class : auto is the default storage class for localvariables
Keyword : auto
8/3/2019 Renesas C Questions
2/28
8/3/2019 Renesas C Questions
3/28
6. Describe about storage allocation and scope of global, extern, static, local and register variables?
a. Global: Scope--- Visible throughout the program execution
Storage : main memory
7. What are enumerations?
a. An enumeration consists of a set of named integer constants. An enumerationtype declaration gives the name of the (optional) enumeration tag and definesthe set of named integer identifiers (called enumerator constants ). A variablewith enumeration type stores one of the values of the enumeration set defined
by that type
enum identifier { enumerator-list }
8. What is the use of typedef?
a. The purpose of typedef is to assign alternative names to existing types. Atypedef declaration does not create types. It creates synonyms for existingtypes, or names for types that could be specified in other ways
9. What is a pointer? What are its advantages?
a. A variable that Holds the address of a variable of some type
b. Adv: *Pointers allow you to implement sharing without copying i.e. pass byreference. *Pointers allow us to use dynamic memory allocation. *Enable toimplement complex data structures and ease string manipulation
10. What is a structure?
a. A structure is a collection of variables under a single name. These variablescan be of different types, and each has a name which is used to select it fromthe structure. A structure is a convenient way of grouping several pieces of related information together. A structure can be defined as a newnamed type
11. What is type-cast? Why is it needed?
a. Typecasting is a way to make a variable of one type, such as an int, act likeanother type, such as a char, for one single operation. To typecast something,simply put the type of variable you want the actual variable to act as inside
parentheses in front of the actual variable
b. One use of typecasts is to force the correct type of mathematical operation to
8/3/2019 Renesas C Questions
4/28
take place
12. What is a const variable?
a. a variable declaration whose value cannot be changed throughout the program. The const keyword is to declare a constant
b. The preprocessor #define is another more flexible method to defineconstants in a program
13. What are the differences between structures and arrays?
a. array -same data type structure -diff datatype
b. Array: Static memory allocation.It uses the subscript to access the arrayelements. Structure: Dynamic memory allocation. It uses thedot(.)operator to access the structure members.
c. Array is a base pointer. It points to a particular memory location.Structure is not a pointer..
14. What are the differences between malloc() and calloc()?
a. void *malloc(size_t size);
The function allocates an object of size_t size (size_t = int, char, float...etc), andreturns the address of the object if successful; otherwise, it returns a null pointer. Thevalues stored in the object are indeterminate
b. void *calloc(size_t nelem, size_t size);
The function allocates an array object containing nelem (number of elements) each of size_t size, stores zeros in all bytes of the array, and returns the address of the firstelement of the array if successful; otherwise, it returns a null pointer
c. malloc allocates memory in bytes whereas calloc allocates memory in blocks
d. malloc takes only one argument and allocates the memory in bytes as given in theargument. calloc takes two arguments, number of variables to be allocated and size of each variable
15. Difference between arrays and linked list?
a. Elements can be inserted into linked lists indefinitely, while an array willeventually either fill up or need to be resized
b. an array from which many elements are removed may become wastefullyempty or need to be made smaller
c. arrays allow random access, while linked lists allow only sequential access to
8/3/2019 Renesas C Questions
5/28
elements. Singly-linked lists, in fact, can only be traversed in one direction
d. disadvantage of linked lists is the extra storage needed for references, whichoften makes them impractical for lists of small data items such as charactersor boolean values
e. LinkedLists are uncomfortable while debugging
16. Can we specify variable field width in a scanf() format string? If possible how?
Yes, you can specify variable width, however you can't specify precision.
the format tags are as follows:
scanf: %[*][width][length]type
17. Out of fgets() and gets() which function is safe to use and why?
a. Reads characters from stdin and stores them as a string into str until anewline character ( '\n' ) or the End-of-File is reached.The ending newline character ( '\n' ) is not included in the string.
A null character ( '\0' ) is automatically appended after the last charactercopied to str to signal the end of the C string.
b. Reads characters from stream and stores them as a C string into str until ( num-1) characters have been read or either a newline or a the End-of-File isreached, whichever comes first. A newline character makes fgets stop reading,
but it is considered a valid character and therefore it is included in the stringcopied to str . A null character is automatically appended in str after thecharacters read to signal the end of the C string.
gets does not let you specify a limit on how many characters are to be read, so youmust be careful with the size of the array pointed by str to avoid buffer overflows
18. What is recursion?
Recursive function is a function that contains a call to itself. Recursive
function allows you to divide your complex problem into identical single
simple cases which can handle easily. Recursive function must have at least
one exit condition that can be satisfied. Otherwise, the recursive function will
call itself repeatedly until the runtime stack overflows.
19. What is difference between Structure and Unions?
8/3/2019 Renesas C Questions
6/28
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
20. What is the difference between Strings and Arrays?
a. In C Strings are defined as arrays of characters
b. In order to allow variable length strings the \0 character is used to indicate theend of a string.
c. string of characters is stored in successive elements of a character array andterminated by the NULL character
d. The remaining elements in the array after the NULL may have any garbagevalues. When the string is retrieved, it will be retrieved starting at index 0 andsucceeding characters are obtained by incrementing the index until the first
NULL character is reached signaling the end of the string
21. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
a. A null pointer has a reserved value, often but not necessarily thevalue zero, indicating that it refers to no object
a null pointer is guaranteed to compare unequal to any valid pointer, whereasdepending on the language and implementation an uninitialized pointer mighthave either an indeterminate (random or meaningless) value or might beinitialised to an initial constant (possibly but not necessarily NULL).
22. What do the c and v in argc and argv stand for?
a. argc" stands for "argument count". It is the number of elements in "argv","argument vector
b. While "argc" and "argv" are theoretically arbitrary parameter names, the useof the names "argc" and "argv" is so standard that you should never use anyother name.
c. The program name itself is argv[0], so the first command-line argument isargv[1], and so on, and argc reflects the total number of items in the argvarray including this argv[0]
23. What is the maximum combined length of command line arguments including the space
http://en.wiktionary.org/wiki/nullhttp://en.wiktionary.org/wiki/null8/3/2019 Renesas C Questions
7/28
between adjacent arguments?
a. There are different ways to learn the upper limit
i. command: getconf ARG_MAX
ii. system call: sysconf(_SC_ARG_MAX)iii. system header: ARG_MAX in e.g.
b. When looking at ARG_MAX/NCARGS, you have to consider the spacecomsumption by both argv[] and envp[] (arguments and environment). Thusyou have to decrease ARG_MAX at least by the results of "env | wc -c" and"env | wc -l * 4" for a good estimation of the currently available space.
c. It depends on the length of the first argument argc. For a 2 byte size thenumber of arguments is 65k and for 4 bytes it is 2^32-1
24. What are bit fields? What is the use of bit fields in a Structure declaration?
Bit Fields allow the packing of data in a structure. This is especially usefulwhen memory or data storage is at a premium. Typical examples:
Packing several objects into a machine word. e.g. 1 bit flags can becompacted -- Symbol tables in compilers.
Reading external file formats -- non-standard file formats could beread in. E.g. 9 bit integers.
C lets us do this in a structure definition by putting : bit length after thevariable. i.e. struct packed_struct {
unsigned int f1:1;unsigned int f2:1;unsigned int f3:1;unsigned int f4:1;unsigned int type:4;unsigned int funny_int:9;
} pack;
Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bittype and a 9 bit funny_int. C automatically packs the above bit fields as compactly as
possible, provided that the maximum length of the field is less than or equal to theinteger word length of the computer.
25. Which bit wise operator is suitable for checking whether a particular bit is on or off? Giveexample.
a. The & (AND) operator
8/3/2019 Renesas C Questions
8/28
short b = 0x50,c;
C = ( b & 0x10 );//checking if bit7 is set or cleared. Result stored in c
26. Which bit wise operator is suitable for turning off a particular bit in a number? Giveexample.
a. The & (AND) operator
short b = 0x50,c;
C = ( b & 0xF0 );//clearing al the bits upto 4 plces from the right. Resultstored in c
27. Which bit wise operator is suitable for putting on a particular bit in a number? GiveExamples
a. The | (OR) operator
short b = 0x50,c;
C = ( b | 0xF0 );//setting al the bits upto 4 plces from the left.Result stored in c
28. Which one is equivalent to multiplying by 2?
a.
8/3/2019 Renesas C Questions
9/28
Method2 (keep the array's contents contiguous)
int **myarray = (int **)malloc(no_of_rows * sizeof(int *));myarray[0] = malloc(no_of_rows * no_of_columns * sizeof(int));
for(i = 1; i < no_of_rows; i++)myarray[i] = myarray[0] + (i * no_of_columns);
// Access elements as myarray[i][j]
30. How can you increase the size of a dynamically allocated array?
realloc
It is often useful to be able to grow or shrink a block of memory. This can be doneusing realloc which returns a pointer to a memory region of the specified size, which containsthe same data as the old region pointed to by ptr (truncated to the minimum of the old andnew 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 maintainsthe original pointer unaltered, and returns the null pointer value. The newly allocated regionof memory is uninitialized (its contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);
If sufficient space exists to expand the memory block pointed to by ptr, the additionalmemory is allocated and the function returns ptr.
If sufficient space does not exist to expand the current block in its current location, anew block of the size for size is allocated, and existing data is copied from the old block tothe beginning of the new block. The old block is freed, and the function returns a pointer tothe new block.
If the ptr argument is NULL, the function acts like malloc(), allocating a block of size bytes and returning a pointer to it.
31. How can you increase the size of a statically allocated array?
int arr[10];
When an array is declared as above, memory is allocated for the elements of thearray when the program starts, and this memory remains allocated during the lifetime of
8/3/2019 Renesas C Questions
10/28
the program. This is known as static array allocation. Hence we cannot increase size of statically allocated array.
32. When reallocating memory if any other pointers point into the same piece of memory do youhave to readjust these other pointers or do they get readjusted automatically?
a. they get readjusted automatically
If sufficient space exists to expand the memory block pointed to by ptr, the
additional memory is allocated and the function returns ptr.
If sufficient space does not exist to expand the current block in its current
location, a new block of the size for size is allocated, and existing data is copied
from the old block to the beginning of the new block. The old block is freed, and thefunction returns a pointer to the new block.
If memory is insufficient for the reallocation (either expanding the old block or
allocating a new one), the function returns NULL, and the original block is
unchanged .
33. Which function should be used to free the memory allocated by calloc()?
a. free () frees the memory space pointed to by ptr , which must have beenreturned by a previous call to malloc (), calloc () or realloc ().
34. How much maximum can you allocate in a single call to malloc()?
a. The largest possible memory block malloc can allocate depends on the hostsystem, particularly the size of physical memory and the operating systemimplementation. Theoretically, the largest number should be the maximumvalue that can be held in a size_t type, which is an implementation-dependentunsigned integer representing the size of an area of memory
35. Can you dynamically allocate arrays in expanded memory?
a. Relloc(), as explained above can be used for this purpose
36. Which header file should you include if you are to develop a function which can accept
8/3/2019 Renesas C Questions
11/28
variable number of arguments?
In order to access the arguments within the called function, the functions declaredin the header file must be included. This introduces a new type, called ava_list, and three functions that operate on objects of this type, called va_start, va_arg,and va_end.
The va_start macro initializes ap for subsequent use by the functions va_arg andva_end. The second argument to va_start, parmN is the identifier naming the rightmost
parameter in the variable parameter list in the function definition (the one just before the ,... )
37. How can a called function determine the number of arguments that have been passed to it?
a. The first argument in the parameter list is generally used to indicate howmany arguments were passed into the function. Otherwise, va_start(,) functionis used to determine the number of arguments in the variable parameter listfunction
b. #include
type va_arg(va_list ap, type);// type holds the count of parameters
38. How do you declare the following:
An array of three pointers to chars Char* c[3];
An array of three char pointers
char (*p)[3];
A pointer to array of three chars
Char *(c[3]);
A pointer to function which receives an int pointer and returns a float pointer
float* (*func)(int *);
A pointer to a function which receives nothing and returns nothing
void (*fun)();
8/3/2019 Renesas C Questions
12/28
39. 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 arandom 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 anargument value of 1.The generator can be set to a new starting point by calling srand witha given seed number.
40. What is the difference between Stack and Heap?
a. The stack is a place in the computer memory where all the variables that aredeclared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime arestored.
b. Stack is a section of memory and its associated registers that is used for temporary storage of information in which the most recently stored item is thefirst to be retrieved. On the other hand, heap is an area of memory used for dynamic memory allocation . Blocks of memory are allocated and freed inthis case in an arbitrary order. The pattern of allocation and size of blocks isnot known until run time
Programming: (Use Makefile to compile the C codes)
1. Write a program to compare two strings without using the strcmp() function.
#include
void stringcmp(char *s1, char *s2)
8/3/2019 Renesas C Questions
13/28
{
int i,j;
for(i=0;*s1!='\0' && *s2 != '\0';s1++,s2++){
if(*s1 != *s2)
{
printf("Strings are different\n");
exit(0);
}
}
printf("String s1:%s \nand \ns2:%s \nare EQUAL\n",s1,s2);
}
int main()
{
char *str1,*str2;
str2 = (char *)malloc(sizeof(char));
str1 = (char *)malloc(sizeof(char));
printf("\nEnter first String:");
scanf("%s",str1);
printf("\nEnter second String:");
scanf("%s",str2);
stringcmp(str1,str2);
8/3/2019 Renesas C Questions
14/28
return 0;
}
2. Write a program to concatenate two strings.
#includeint main(){
int i=0,j=0;
char *str1,*str2;
str2 = (char *)malloc(sizeof(char));
str1 = (char *)malloc(sizeof(char));
puts("Enter first string");
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before concatenation the strings are\n");
puts(str1); puts(str2);
while(*str1!='\0'){
str1++;
i++;
}
i--;
while(*str2!='\0'){
*str1++=*str2++;
i++;//str1++; str2++;
}
*str1='\0';
while(i>=0){
i--;
8/3/2019 Renesas C Questions
15/28
str1--;
}
printf("After concatenation the strings are\n");
puts(str1);return 0;
}
3. Write a program to interchange 2 variables without using the third one.
#include
main()
{
int a,b;
printf("Enter the first no : ");
scanf("%d",&a);
printf("Enter the second no : ");
scanf("%d",&b);
printf("a = %d, b = %d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("a = %d, b = %d\n",a,b);
}
4. Write programs for String Reversal. The same for Palindrome check.
#include
#include
main()
8/3/2019 Renesas C Questions
16/28
8/3/2019 Renesas C Questions
17/28
}
5. How would you implement a substr() function that extracts a sub string from a givenstring?
#include
#include
main(){
const char* from ;
char *to;
int b,e;
printf("Enter the str : ");
gets(from);
puts("\nEnter start ans end positions of the substring\n");
scanf("%d %d",&b,&e);
to=strndup(from+b-1, e-1);
puts(to);
}
6. Write a program to find the Factorial of a number.
#include
int main(){
int i=1,f=1,num;
printf("\nEnter a number:");
scanf("%d",&num);
while(i
8/3/2019 Renesas C Questions
18/28
}
7. Write a program which employs Recursion? (Factorial)
#include
int main(){int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d\n",num,f);
return 0;
}
int fact(int n){
if(n==1)
return 1;
else
return(n*fact(n-1));
}
8. Write a program to generate the Fibonacci Series?
#include
int fib(int a);
main()
{
int a,i;
puts("Enter number for fibonacci : ");
scanf("%d",&a);
8/3/2019 Renesas C Questions
19/28
for(i=0;i
8/3/2019 Renesas C Questions
20/28
{
int i;
char c[4];
}u;
int main()
{
u temp;
temp.i = 0x12345678;
printf("%x\n", temp.i);
printf("%x %x %x %x\n", temp.c[0], temp.c[1], temp.c[2], temp.c[3]);
}
int main()
{
int num=1;
char *cptr;
cptr = (char *)#
if (*cptr)
printf ("little endian\n");
else printf ("big endian\n");
return 0;
}
8/3/2019 Renesas C Questions
21/28
11. Write the following Linked List programs:
i. Add a node at top
ii. Delete a node at top
iii. Add a node at endiv. Delete a node at end
v. Insert a node at Nth location
vi. Delete a node at Nth location
vii. To return of number of nodes in the list.
viii. Reverse a Linked list.
****************Program maintains a list of Names*****************
#include
#include
struct line {
char name[20];
struct line *next;
};
struct line *start= NULL; /* pointer to first entry in list */
struct line *last= NULL; /* pointer to last entry */
int list(int n){
struct line *p;
p = start;
printf("\nList has . . \n");
while(p){
printf(p->name);
puts("\n");
if(!p->next) break;
8/3/2019 Renesas C Questions
22/28
p=p->next;n++;
}
return n;
}
void middle(struct line *i, /* new element to store */
struct line **start, /* start of list */
struct line **last,int n) /* end of list */
{
struct line *old, *p;
p = *start;
if(!(*last)) { /* first element in list */
i->next = NULL;
*last = i;
*start = i;
return;
}
if(n==0){
i->next = p; /* new first element */
*start = i;
return;
}
old = NULL;
while(n>=0) {
n--;
old = p;
p = p->next;
8/3/2019 Renesas C Questions
23/28
if(!p->next) break;
}
if(old) { /* goes in middle */old->next = i;
i->next = p;
return;
}
(*last)->next = i; /* put on end */
i->next = NULL;
*last = i;
}
void midel(
//struct line *i, /* item to delete */
struct line **start, /* start of list */
struct line **last,
int n) /* end of list */
{
struct line *p,*old;
p=*start;
old = NULL;
n-=2;
if(nnext;
8/3/2019 Renesas C Questions
24/28
return;
}
while(n>=0) {
n--;old = p;
p = p->next;
if(!p->next) break;
}
//printf(p->name);
//else *start = i->next;
if(p==*last && p){
*last = p;
free(p);
return;
}
if(p) old->next = p->next;
free(p);
}
void edel(struct line **start,struct line **last){
struct line *p;
p = *start;
if(p==*last && p){
*last = p;
free(p);
return;
}
8/3/2019 Renesas C Questions
25/28
while(p->next != *last) p = p->next;
*last = p;
(*last)->next = NULL;
}
void end(struct line *i,
struct line **last)
{
if(!(*last)) *last = i; /* first item in list */
else (*last)->next = i;
i->next = NULL;
*last = i;
}
void top(struct line *i,
struct line **start)
{
if(!(*start)) *start = i; /* first item in list */
else i->next = *start; /* new first element */
*start = i;
}
void reverse(struct line **start){
struct line *p,*q,*r;
p = *start;
q = NULL;
while(p!=NULL)
8/3/2019 Renesas C Questions
26/28
{
r=q;
q=p;
p=p->next;q->next=r;
}
*start = q;
printf("\n Reverse list is . . \n");
list(0);
}
int menu(){
int wish;
printf("\n1.Insert new element\n2.Add element at a position\n3.Add element to thetop\n4.Add element to end\n5.Delete element at a position\n6.Delete element at thetop\n7.Delete element at the end\n8.Invert linked list\n9.Display elements \nPress 0 to quit\n");
scanf("%d",&wish);if(!wish) exit(0);
return wish;
}
struct line* enter(){
struct line *i;
char nam[20];
i = (struct line*)malloc(sizeof(struct line));
puts("\nEnter name : ");
scanf("%s",&nam);
8/3/2019 Renesas C Questions
27/28
strcpy(i->name,nam);
return i;
}
main(){
int n;
struct line *i;
start = last = NULL; /* initialize start and end pointers */
for(;;) {
switch (menu()) {
case 1: i = enter();
break;
case 2: printf("\nEnter position : ");
scanf("%d",&n);
middle(i,&start,&last,n);
n = list(0);
break;
case 3: middle(i,&start,&last,0);
n = list(0);
break;
case 4: n = list(n);
printf("\nNew element is added to end . .\n");
end(i,&last);
n = list(0);
break;
case 5: printf("\nEnter position : ");
scanf("%d",&n);
8/3/2019 Renesas C Questions
28/28
midel(&start,&last,n);
n = list(0);
break;
case 6: midel(&start,&last,0);n = list(0);
break;
case 7: n = list(n);
n -= 2;
printf("\n%Last element is deleted . .\n");
edel(&start,&last);
n = list(0);
break;
case 8: reverse(&start);
break;
default:n = list(n);
break;
}
}
}