Sie sind auf Seite 1von 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 the

entire code under the name is executed. The block of code is communicated to the 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 involve function 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 an

argument in the calling function to a corresponding parameter in the called function using pointers. *The value of the argument in the calling
function can be modified by the called function. b. In pass-by-value, the compiler copies the value of an argument in a calling

function to a corresponding non-pointer parameter in the called function definition. *The changes in the called function will not be reflected in the calling 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. A separate 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 has

external linkage (its name is visible from files other than the one in which it's defined). 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 life time of variables and/or functions. b. auto - storage class : auto is the default storage class for local variables Keyword : auto

Storage Location : Main memory Initial Value : Garbage Value Life : Control remains in a block where it is defined. Scope : Local to the block in which variable is declared.

register - Storage Class : stored in a register. Register is used to


define local variables that should be stored in a register instead of RAM. The variable has a maximum size equal to the register size. Register variables occur in CPU and value of that register variable is stored in a register within that CPU. Thus, it increases the resultant speed of operations.
o o o o o

Keyword : register Storage Location : CPU Register Initial Value : Garbage Life : Local to the block in which variable is declared. Scope : Local to the block

static is the default storage class for global variables


o o o o o

Keyword : static Storage Location : Main memory Initial Value : Zero and can be initialize once only. Life : depends on function calls and the whole application or program. Scope : Local to the block.

extern - storage Class : extern defines a global variable that is visible to ALL object modules. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
o o o o o

Keyword : extern Storage Location : Main memory Initial Value : Zero Life : Until the program ends. Scope : Global to the program.

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 enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers (called enumerator constants ). A variable with 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. A

typedef declaration does not create types. It creates synonyms for existing types, 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 by

reference. *Pointers allow us to use dynamic memory allocation. *Enable to implement 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 variables

can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together. A structure can be defined as a new
named 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 like another 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

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 define constants 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 array elements. Structure: Dynamic memory allocation. It uses the dot(.)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), and returns the address of the object if successful; otherwise, it returns a null pointer. The values 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 first element 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 the argument. 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 will eventually either fill up or need to be resized b. an array from which many elements are removed may become wastefully empty or need to be made smaller c. arrays allow random access, while linked lists allow only sequential access to

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, which often makes them impractical for lists of small data items such as characters or 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 a newline 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 character copied 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 is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters 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 you must 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?

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 the

end of a string. c. string of characters is stored in successive elements of a character array and terminated by the NULL character d. The remaining elements in the array after the NULL may have any garbage values. When the string is retrieved, it will be retrieved starting at index 0 and succeeding 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 the value zero, indicating that it refers to no object

a null pointer is guaranteed to compare unequal to any valid pointer, whereas depending on the language and implementation an uninitialized pointer might have either an indeterminate (random or meaningless) value or might be initialised 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 use

of the names "argc" and "argv" is so standard that you should never use any other name.
c. The program name itself is argv[0], so the first command-line argument is

argv[1], and so on, and argc reflects the total number of items in the argv array including this argv[0] 23. What is the maximum combined length of command line arguments including the space

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. <[sys/]limits.h> b. When looking at ARG_MAX/NCARGS, you have to consider the space

comsumption by both argv[] and envp[] (arguments and environment). Thus you 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 the number 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 useful when memory or data storage is at a premium. Typical examples: Packing several objects into a machine word. e.g. 1 bit flags can be compacted -- Symbol tables in compilers.

Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers. C lets us do this in a structure definition by putting :bit length after the variable. i.e. struct packed_struct {
unsigned unsigned unsigned unsigned unsigned unsigned } pack; int int int int int int f1:1; f2:1; f3:1; f4:1; type:4; funny_int:9;

Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type 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 the integer word length of the computer.

25. Which bit wise operator is suitable for checking whether a particular bit is on or off? Give

example. a. The & (AND) operator

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? Give

example. a. The & (AND) operator short b = 0x50,c; C = ( b & 0xF0 );//clearing al the bits upto 4 plces from the right. Result stored in c
27. Which bit wise operator is suitable for putting on a particular bit in a number? Give

Examples
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. << 29. How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
a. One dimensional array int *myarray = malloc(no_of_elements * sizeof(int)); //Access elements as myarray[i]

Two dimensional array Method1 int **myarray = (int **)malloc(no_of_rows * sizeof(int *)); for(i = 0; i < no_of_rows; i++) { myarray[i] = malloc(no_of_columns * sizeof(int)); } // Access elements as myarray[i][j]

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 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); 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 the function returns a pointer to the 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 the array when the program starts, and this memory remains allocated during the lifetime of

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 you have 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 the function 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 been

returned 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 host system, particularly the size of physical memory and the operating system implementation. Theoretically, the largest number should be the maximum value that can be held in a size_t type, which is an implementation-dependent unsigned 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

variable number of arguments? In order to access the arguments within the called function, the functions declared in the <stdarg.h> header file must be included. This introduces a new type, called a va_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 and va_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 how

many arguments were passed into the function. Otherwise, va_start(,) function is used to determine the number of arguments in the variable parameter list function b. #include <stdarg.h> 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)();

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 (num1).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.

40. What is the difference between Stack and Heap?


a. The stack is a place in the computer memory where all the variables that are

declared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime are stored.
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 the first 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 in this case in an arbitrary order. The pattern of allocation and size of blocks is not 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 <string.h> void stringcmp(char *s1, char *s2)

{ 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);

return 0; } 2. Write a program to concatenate two strings. #include<stdio.h> int 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--;

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<stdio.h> 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<stdio.h> #include<string.h> main()

{ char *str,*revstr;int i=0,j=0; str = (char *)malloc(sizeof(char));

printf("Enter the string to be reversed : "); scanf("%s",str); while(*str != '\0'){ str++;i++; } revstr = (char *)malloc(sizeof(char)); str--; for(;i>0;i--) { *revstr++ = *str--; j++; } str++; *revstr='\0'; while(j>0){ revstr--;j--; } printf("Input String : %s",str); printf("\nReverse String : %s\n",revstr); if(!strcmp(revstr,str)) printf("String is palindrome\n"); else printf("Strings are not palindrome\n");

} 5. How would you implement a substr() function that extracts a sub string from a given string? #include <string.h> #include<stdio.h> 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<stdio.h> int main(){ int i=1,f=1,num; printf("\nEnter a number:"); scanf("%d",&num); while(i<=num){ f=f*i; i++; } printf("\nFactorial of %d is:%d\n",num,f); return 0;

} 7. Write a program which employs Recursion? (Factorial) #include<stdio.h> 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<stdio.h> int fib(int a); main() { int a,i; puts("Enter number for fibonacci : "); scanf("%d",&a);

for(i=0;i<a;i++) printf("%d\n",fib(i)); }

int fib(int n) { if (n <= 1) return n; else return fib(n-1)+fib(n-2); } 9. Write a program which uses command line arguments. #include<stdio.h> main(int argc,char *argv[]){ int i; printf("You entered . . .%d arguments\n",argc-1);

for (i = 1; i < argc; i++)

printf("%s in %d position\n",argv[i],i); } 10. Write a function to check the endianness of a processor #include <stdio.h>

typedef union

{ 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 *)&num;

if (*cptr) printf ("little endian\n"); else printf ("big endian\n");

return 0; }

11. Write the following Linked List programs: i. ii. iii. iv. v. vi. vii. viii. Add a node at top Delete a node at top Add a node at end Delete a node at end Insert a node at Nth location Delete a node at Nth location To return of number of nodes in the list. Reverse a Linked list.

****************Program maintains a list of Names***************** #include<stdio.h> #include<string.h> 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;

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;

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(n<=0){ *start = (*start)->next;

return; } while(n>=0) { n--; old = p; p = p->next; if(!p->next) } //printf(p->name); //else *start = i->next; if(p==*last && p){ *last = p; free(p); return; } if(p) old->next = p->next; free(p); } break;

void edel(struct line **start,struct line **last){ struct line *p; p = *start; if(p==*last && p){ *last = p; free(p); return; }

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)

{ 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 the top\n4.Add element to end\n5.Delete element at a position\n6.Delete element at the top\n7.Delete element at the end\n8.Invert linked list\n9.Display elements \n Press 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);

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);

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; } } }