Skip to main content

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  

Popular posts from this blog

Story Books of Rabindranath Thakur

Story Books of Tintin & Harry Potter