How do I determine amount of memory currently available for allocating?
We can use function coreleft( ) to get the amount of memory available for allocation. However, this function does not give an exact amount of unused memory. If, we are using a small memory model, coreleft( ) returns the amount of unused memory between the top of the heap and stack. If we are using a larger model, this function returns the amount of memory between the highest allocated memory and the end of conventional memory. The function returns amount of memory in terms of bytes.
How does a C program come to know about command line arguments?
When we execute our C program, operating system loads the program into memory. In case of DOS, it first loads 256 bytes into memory, called program segment prefix. This contains file tables,environment segment, and command line information. When we compile the C program the compiler inserts additional code that parses the command, assigning it to the argv array, making the arguments easily accessible within our C program.
What is environment and how do I get environment for a specific entry?
While working in DOS, it stores information in a memory region called environment. In this region we can place configuration settings such as command path, system prompt, etc. Sometimes in a program we need to access the information contained in environment. The function getenv( ) can be used when we want to access environment for a specific entry. Following program demonstrates the use of this function.
#include
main( )
{
char *path = NULL ;
path = getenv ( "PATH" ) ;
if ( *path != NULL )
printf ( "\nPath: %s", path ) ;
else
printf ( "\nPath is not set" ) ;
}
How do I display current date in the format given below?
Following program illustrates how we can display date in above given format.
#include
main( )
{
struct tm *curtime ;
time_t dtime ;
char str[30] ;
time ( &dtime ) ;
curtime = localtime ( &dtime ) ;
strftime ( str, 30, "%A %B %d, %Y", curtime ) ;
printf ( "\n%s", str ) ;
}
Here we have called time( ) function which returns current time. This time is returned in terms of seconds, elapsed since 00:00:00 GMT, January 1, 1970. To extract the week day, day of month, etc.from this value we need to break down the value to a tm structure. This is done by the function localtime( ). Then we have called strftime( ) function to format the time and store it in a string str.
How can I find the day of the week of a given date?
The following code snippet shows how to get the day of week from the given date.
dayofweek ( int yy, int mm, int dd )
{
/*Monday = 1 and Sunday = 0 */
/* month number >= 1 and <= 12, yy > 1752 or so */
static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;
yy = yy - mm < 3 ;
return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] + dd ) % 7 ;
}
void main( )
{
printf ( "\n\n\nDay of week %d ", dayofweek ( 2002, 5, 18 ) ) ;
}
What's the difference between these two declarations?
struct str1 { ... } ;
typedef struct { ... } str2 ;
The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.
How do I print the contents of environment variables?
The following program shows how to achieve this
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( "\n%s", env[ i++ ] ) ;
}
main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables.
How do I use the function ldexp( ) in a program?
The math function ldexp( ) is used while solving the complex mathematical equations. This function takes two arguments, a double value and an int respectively. The order in which ldexp( ) function performs calculations is ( n * pow ( 2, exp ) ) where n is the double value and exp is the integer. The following program demonstrates the use of this function.
#include
void main( )
{
double ans ;
double n = 4 ;
ans = ldexp ( n, 2 ) ;
printf ( "\nThe ldexp value is %lf\n", ans ) ;
}
Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is 16.000000
When we open a file, how does functions like fread( )/fwrite( ), etc. get to know from where to read or to write the data?
When we open a file for read/write operation using function like fopen( ), it returns a pointer to the structure of type FILE. This structure stores the file pointer called position pointer, which keeps track of current location within the file. On opening file for read/write operation, the file pointer is set to the start of the file. Each time we read/write a character, the position pointer advances one character. If we read one line of text at a step from the file, then file pointer advances to the start of the next line. If the file is opened in append mode, the file pointer is placed at the very end of the file. Using fseek( ) function we can set the file pointer to some other place within the file.
Explain the use of array indices ?
If we wish to store a character in a char variable ch and the character to be stored depends on the value of another variable say color (of type int), then the code would be as shown below:
switch ( color )
{
case 0 :
ch = 'R' ;
break ;
case 1 :
ch = 'G' ;
break ;
case 2 :
ch = 'B' ;
break ;
}
How do I write code that would get error number and display error message if any standard error occurs?
Following code demonstrates this.
#include
main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( "C:\file.txt", "r" ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( "\n%s", errmsg ) ;
}
}
Here, we are trying to open 'file.txt' file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in 'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.
How do I write code to get the current drive as well as set the current drive?
The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates 'A' as the current drive, 1 as 'B' and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.
#include
main( )
{
int dno, maxdr ;
dno = getdisk( ) ;
printf ( "\nThe current drive is: %c\n", 65 + dno
) ;
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( "\nNow the current drive is: %c\n", 65 +
dno ) ;
}
How do I compare character data stored at two different memory locations?
Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.
#include
main( )
{
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ;
int c ;
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memcmp are identical" ) ;
else
printf ( "\nStrings arr1 and arr2 compared using memcmp are not identical") ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memicmp are identical" );
else
printf ( "\nStrings arr1 and arr2 compared using memicmp are not identical" ) ;
}
Fixed-size objects are more appropriate as compared to variable size data objects. Using variable-size data objects saves very little space. Variable size data objects usually have some overhead. Manipulation of fixed-size data objects is usually faster and easier. Use fixed size when maximum size is clearly bounded and close to average. And use variable-size data objects when a few of the data items are bigger than the average size. For example,
char *num[10] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;
Instead of using the above, use
char num[10][6] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;
The first form uses variable-size data objects. It allocates 10 pointers, which are pointing to 10 string constants of variable size. Assuming each pointer is of 4 bytes, it requires 90 bytes. On the other hand, the second form uses fixed size data objects. It allocates 10 arrays of 6 characters each. It requires only 60 bytes of space. So, the variable-size in this case does not offer any advantage over fixed size.
Why doesn't the following statement work?char str[ ] = "Hello" ;
strcat ( str, '!' ) ;
The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:
strcat ( str, "!" ) ;
Malloc() Function- What is the difference between "calloc(...)" and "malloc(...)"?
1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).
malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).
2.malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.
What does static variable mean?
There are 3 main uses for the static.
1. If you declare within a function:It retains the value between function calls
2.If it is declared for a function name:By default function is extern..so it will be visible from other files if the function declaration is as static..it is invisible for the outer files
3. Static for global variables:By default we can use the global variables from outside files If it is static global..that variable is limited to with in the file
What are the differences between malloc() and calloc()?
There are 2 differences.First, is in the number of arguments. malloc() takes a single argument(memory required in bytes), while calloc() needs 2 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.
Difference between const char* p and char const* p?
In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location. in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.
How can you determine the size of an allocated portion of memory?
You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.
What is the difference between ordinary variable and pointer in C?
An ordinary variable is like a container it can hold any value and we can change the value of ordinary variable at a time throughout the program .A pointer is a variable that stores the address of another Variable.
What are segment and offset addresses?
When paging technique is performed, the page will breaks into segments and its sequence is said to be segments and its width can be said as offset. In short,segment is a physical address and offset is logical address.
What is "far" and "near" pointers in "c" ?
“Near" and "far" pointers are actually non-standard qualifiers that you'll find only on x86 systems. They reflect the odd segmentation architecture of Intel processors. In short, a near pointer is an offset only,which refers to an address in a known segment. A far pointer is a compound value, containing both a segment number and an offset into that segment. Segmentation still exists on Intel processors, but it is not used in any of the mainstream 32-bit operating systems developed for them, so you'll generally only find the "near" and "far" keywords in source code developed for Windows 3.x,MS-DOS, Xenix/80286, etc.
When should a type cast be used?
There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));
What is the difference between %d and %*d in c language?
%d give the original value of the variable and %*d give the address of the variable.
eg:-int a=10,b=20;
printf("%d%d",a,b);
printf("%*d%*d",a,b);
Result is 10 20 1775 1775 .Here 1775 is the starting address of the memory allocation for the integer.a and b having same address because of contagious memory allocation.
Exactly what does static variable indicate?
There are actually three major purposes of the static.
1. If you declare inside a function:
It keeps the value between function calls
2.If it is declared for a function name:
By default function is actually extern.therefore it is going to be visible from all other files if the function declaration is as static..it is invisible for the external files
3. Static for global variables:
By default we are able to make use of the global variables from outside files when it is static global.that variable is restricted to within the file.
What are the various storage classes within C?
C has 3 kinds of storage: automatic, static and allocated.
Variable getting block scope and also without having static specifier have automatic storage duration.
Variables along with block scope, and with static specifier have static scope. Global variables (i.e, file scope) with or without the static specifier also provide static scope.
Memory extracted from calls to malloc(), alloc() or realloc() is allocated storage class.
Can static variables be declared within a header file?
You can not declare a static variable without defining it as well (this is really because the actual storage class modifiers static and also extern are mutually exclusive). A static variable could be defined in a header file, but this would cause each source file that included the header file to get its very own private copy from the variable, which is most likely not what was meant
Can a variable become both constant and volatile?
Yes. The const modifier implies that this particular program code cannot change the value of the actual variable, but that will not imply that the value can not be changed by means outside this code. For instance, within the example in frequently asked questions, the timer structure was accessed through a volatile const pointer.The function by itself did not change the value of the timer, so it had been declared const. However, the value had been changed by hardware on the computer, so it was declared volatile. If a variable is both equally const and volatile, the two modifiers can come in either order.
Can include records end up being nested?
Certainly. Incorporate records might be nested any number regarding situations. So long as you use precautionary actions, you can stay away from including the same report two times. In the past, nesting header records appeared to be noticed since awful licensed users training, because doing so complicates that dependency administering perform in the help make system and therefore slows along collection. Nearly all today’s famous compilers constitute because of this frustration through putting into action any idea referred to as precompiled headers, through which almost all headers in addition to linked dependencies tend to be saved in the precompiled state.
A good number of developers love to create a custom made header report which includes #include phrases for each header necessary for every module. This can be completely satisfactory and may aid stay away from potential wounds with regards to #include records, for example by chance omitting a good #include report in the module.
What is a null pointer?
There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*.
Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure.
2) As an error value.
3) As a sentinel value.
What is the difference between printf() and sprintf() ?
sprintf() writes data to the character array whereas printf(...) writes data to the standard output device.
What is the output of printf("%d") ?
1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.
2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.
3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).
malloc()
No comments:
Post a Comment