C Programming

  Home  Computer Programming  C Programming


“C Programming Interview Questions and Answers will guide you that C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories and C language is for use with the Unix operating system. If you are developer and need to update your software development knowledge regarding basic and advance C programming or need to prepare for a job interview? Check out this collection of basic and advance C programing Interview Questions and Answers.”



221 C Programming Questions And Answers

41⟩ Why isnt any of this standardized in C? Any real program has to do some of these things.

Actually, some standardization has occurred along the way. In the beginning, C did not have a standard library at all; programmers always had to ``roll their own'' utility routines. After several abortive attempts, a certain set of library routines (including the str* and stdio families of routines) became a de facto standard, at least on Unix systems, but the library was not yet a formal part of the language. Vendors could (and occasionally did) provide completely different routines along with their compilers.

In ANSI/ISO Standard C, a library definition (based on the 1984 /usr/group standard, and largely compatible with the traditional Unix library) was adopted with as much standing as the language itself. The Standard C library's treatment of file and device I/O is, however, rather minimal. It states how streams of characters are written to and read from files, and it provides a few suggestions about the display behavior of control characters like b, r, and t, but beyond that it is silent. (Many of these issues are, however, addressed and standardized in Posix.)

If the Standard were to attempt to define standard mechanisms for accessing things like keyboards and displays, it might seem to be a big convenience for programmers. But it would be a monumental task: there is already a huge variety of display devices, and huge variation among the operating systems through which they are usually accessed. We cannot assume that the years to come will offer any less variety.

 113 views

42⟩ What are near and far pointers?

These days, they're pretty much obsolete; they're definitely system-specific. They had to do with 16-bit programming under MS-DOS and perhaps some early versions of Windows. If you really need to know, see a DOS- or Windows-specific programming reference. If you're using a machine which doesn't require (or permit) making the near/far pointer distinction, just delete the unnecessary ``near'' and ``far'' keywords (perhaps using the preprocessor: ``#define far /* nothing */'').

 106 views

43⟩ But I cant use all these nonstandard, system-dependent functions, because my program has to be ANSI compatible!

You're out of luck. Either you misunderstood your requirement, or it's an impossible one to meet. ANSI/ISO Standard C simply does not define ways of doing these things; it is a language standard, not an operating system standard. An international standard which does address many of these issues is POSIX (IEEE 1003.1, ISO/IEC 9945-1), and many operating systems (not just Unix) now have POSIX-compatible programming interfaces.

It is possible, and desirable, for most of a program to be ANSI-compatible, deferring the system-dependent functionality to a few routines in a few files which are either heavily #ifdeffed or rewritten entirely for each system ported to;

 107 views

44⟩ I am trying to compile this program

I'm trying to compile this program, but the compiler is complaining that ``union REGS'' is undefined, and the linker is complaining that int86 is undefined.

Those have to do with MS-DOS interrupt programming. They don't exist on other systems.

 90 views

45⟩ How can I ensure that integer arithmetic doesnt overflow?

The usual approach is to test the operands against the limits in the header file <limits.h> before doing the operation. For example, here is a ``careful'' addition function:

int

chkadd(int a, int b)

{

if(INT_MAX - b < a) {

fputs("int overflown", stderr);

return INT_MAX;

}

return a + b;

}

 102 views

47⟩ How can I trap or ignore keyboard interrupts like control-C?

The basic step is to call signal, either as

#include <signal.h>

signal(SIGINT, SIG_IGN);

to ignore the interrupt signal, or as

extern void func(int);

signal(SIGINT, func);

to cause control to transfer to function func on receipt of an interrupt signal.

On a multi-tasking system such as Unix, it's best to use a slightly more involved technique:

extern void func(int);

if(signal(SIGINT, SIG_IGN) != SIG_IGN)

signal(SIGINT, func);

The test and extra call ensure that a keyboard interrupt typed in the foreground won't inadvertently interrupt a program running in the background (and it doesn't hurt to code calls to signal this way on any system).

On some systems, keyboard interrupt handling is also a function of the mode of the terminal-input subsystem; On some systems, checking for keyboard interrupts is only performed when the program is reading input, and keyboard interrupt handling may therefore depend on which input routines are being called (and whether any input routines are active at all). On MS-DOS systems, setcbrk or ctrlbrk functions may also be involved.

 101 views

48⟩ How can I implement a delay, or time a users response, with sub-second resolution?

Unfortunately, there is no portable way. Routines you might look for on your system include clock, delay, ftime, gettimeofday, msleep, nap, napms, nanosleep, setitimer, sleep, Sleep, times, and usleep. (A function called wait, however, is at least under Unix not what you want.) The select and poll calls (if available) can be pressed into service to implement simple delays. On MS-DOS machines, it is possible to reprogram the system timer and timer interrupts.

Of these, only clock is part of the ANSI Standard. The difference between two calls to clock gives elapsed execution time, and may even have subsecond resolution, if CLOCKS_PER_SEC is greater than 1. However, clock gives elapsed processor time used by the current program, which on a multitasking system (or in a non-CPU-intensive program) may differ considerably from real time.

If you're trying to implement a delay and all you have available is a time-reporting function, you can implement a CPU-intensive busy-wait, but this is only an option on a single-user, single-tasking machine, as it is terribly antisocial to any other processes. Under a multitasking operating system, be sure to use a call which puts your process to sleep for the duration, such as sleep or select, or pause in conjunction with alarm or setitimer.

For really brief delays, it's tempting to use a do-nothing loop like

long int i;

for(i = 0; i < 1000000; i++)

;

 103 views

49⟩ How can I read in an object file and jump to locations in it?

You want a dynamic linker or loader. It may be possible to malloc some space and read in object files, but you have to know an awful lot about object file formats, relocation, etc., and this approach can't work if code and data reside in separate address spaces or if code is otherwise privileged.

Under BSD Unix, you could use system and ld -A to do the linking for you. Many versions of SunOS and System V have the -ldl library containing routines like dlopen and dlsym which allow object files to be dynamically loaded. Under VMS, use LIB$FIND_IMAGE_SYMBOL. GNU has a package called ``dld''.

 160 views

50⟩ Is exit(status) truly equivalent to returning the same status from main?

Yes and no. The Standard says that a return from the initial call to main is equivalent to calling exit. However, a return from main cannot be expected to work if data local to main might be needed during cleanup; A few very old, nonconforming systems may once have had problems with one or the other form. (Finally, the two forms are obviously not equivalent in a recursive call to main.)

 95 views

51⟩ How can I open files mentioned on the command line, and parse option flags?

Here is a skeleton which implements a traditional Unix-style argv parse, handling option flags beginning with -, and optional filenames. (The two flags accepted by this example are -a and -b; -b takes an argument.)

#include <stdio.h>

#include <string.h>

#include <errno.h>

main(int argc, char *argv[])

{

int argi;

int aflag = 0;

char *bval = NULL;

for(argi = 1; argi < argc && argv[argi][0] == '-'; argi++) {

char *p;

for(p = &argv[argi][1]; *p != ''; p++) {

switch(*p) {

case 'a':

aflag = 1;

printf("-a seenn");

break;

case 'b':

bval = argv[++argi];

printf("-b seen ("%s")n", bval);

break;

default:

fprintf(stderr,

"unknown option -%cn", *p);

}

}

}

if(argi >= argc) {

/* no filename arguments; process stdin */

printf("processing standard inputn");

} else {

/* process filename arguments */

for(; argi < argc; argi++) {

FILE *ifp = fopen(argv[argi], "r");

if(ifp == NULL) {

fprintf(stderr, "can't open %s: %sn",

argv[argi], strerror(errno));

continue;

}

printf("processing %sn", argv[argi]);

fclose(ifp);

}

}

return 0;

}

 106 views

52⟩ How can a process change an environment variable in its caller?

It may or may not be possible to do so at all. Different operating systems implement global name/value functionality similar to the Unix environment in different ways. Whether the ``environment'' can be usefully altered by a running program, and if so, how, is system-dependent.

Under Unix, a process can modify its own environment (some systems provide setenv or putenv functions for the purpose), and the modified environment is generally passed on to child processes, but it is not propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD ``tset'' program in .profile and .login files effects such a scheme.) Under MS-DOS, it's possible to manipulate the master copy of the environment, but the required techniques are arcane.

 111 views

53⟩ How can I automatically locate a programs configuration files in the same directory as the executable?

It's hard, in general; Even if you can figure out a workable way to do it, you might want to consider making the program's auxiliary (library) directory configurable, perhaps with an environment variable. (It's especially important to allow variable placement of a program's configuration files when the program will be used by several people, e.g. on a multiuser system.)

 115 views

55⟩ How can I invoke another program or command and trap its output?

Unix and some other systems provide a popen function, which sets up a stdio stream on a pipe connected to the process running a command, so that the calling program can read the output (or alternatively supply the input). Using popen,

extern FILE *popen();

sprintf(cmdbuf, "sort < %s", datafile);

fp = popen(cmdbuf, "r");

/* ...now read sorted data from fp... */

pclose(fp);

(Do be sure to call pclose, as shown; leaving it out will seem to work at first but may eventually run you out of processes or file descriptors.)

If you can't use popen, you may be able to use system, with the output going to a file which you then open and read,

If you're using Unix and popen isn't sufficient, you can learn about pipe, dup, fork, and exec.

(One thing that probably would not work, by the way, would be to use freopen.)

 110 views

57⟩ How can I call system when parameters (filenames, etc.) of the executed command arent known until run time?

Just use sprintf (or perhaps strcpy and strcat) to build the command string in a buffer, then call system with that buffer. (Make sure the buffer is allocated with enough space;

Here is a contrived example suggesting how you might build a data file, then sort it (assuming the existence of a sort utility, and Unix- or MS-DOS-style input/output redirection):

char *datafile = "file.dat";

char *sortedfile = "file.sort";

char cmdbuf[50];

FILE *fp = fopen(datafile, "w");

/* ...write to fp to build data file... */

fclose(fp);

sprintf(cmdbuf, "sort < %s > %s", datafile, sortedfile);

system(cmdbuf);

fp = fopen(sortedfile, "r");

/* ...now read sorted data from fp... */

 115 views

58⟩ How can I invoke another program (a standalone executable, or an operating system command) from within a C program?

Use the library function system, which does exactly that.

Some systems also provide a family of spawn routines which accomplish approximately the same thing. system is more ``portable'' in that it is required under the ANSI C Standard, although the interpretation of the command string--its syntax and the set of commands accepted--will obviously vary tremendously.

The system function ``calls'' a command in the manner of a subroutine, and control eventually returns to the calling program. If you want to overlay the calling program with another program (that is, a ``chain'' operation) you'll need a system-specific routine, such as the exec family on Unix.

Note that system's return value is at best the command's exit status (although even that is not guaranteed), and usually has nothing to do with the output of the command.

 115 views

59⟩ How can I do PEEK and POKE in C?

How can I access memory (a memory-mapped device, or graphics memory) located at a certain address? How can I do PEEK and POKE in C?

Set a pointer, of the appropriate type, to the right number (using an explicit cast to assure the compiler that you really do intend this nonportable conversion):

unsigned int *magicloc = (unsigned int *)0x12345678;

Then, *magicloc refers to the location you want. If the location is a memory-mapped I/O register, you will probably also want to use the volatile qualifier: ``volatile unsigned int *magicloc''. (If you want to refer to a byte at a certain address rather than a word, use unsigned char *.)

Under MS-DOS, you may find a macro like MK_FP() handy for working with segments and offsets. As suggested by Gary Blaine, you can also declare tricky array pointers which allow you to access screen memory using array notation. For example, on an MS-DOS machine in an 80x25 text mode, given the declaration

unsigned short (far * videomem)[80] =

(unsigned short (far *)[80])0xb8000000;

you can access the character and attribute byte at row i, column j with videomem[i][j].

Many operating systems execute user-mode programs in a protected mode where direct access to I/O devices (or to any address outside the running process) is simply not possible. In such cases you will have to ask the operating system to carry out I/O operations for you.

 97 views

60⟩ I thought that using large model meant that I could use more than 64K of data!

Q: What does the error message ``DGROUP data allocation exceeds 64K'' mean, and what can I do about it? I thought that using large model meant that I could use more than 64K of data!

A: Even in large memory models, MS-DOS compilers apparently toss certain data (strings, some initialized global or static variables) into a default data segment, and it's this segment that is overflowing. Either use less global data, or, if you're already limiting yourself to reasonable amounts (and if the problem is due to something like the number of strings), you may be able to coax the compiler into not using the default data segment for so much. Some compilers place only ``small'' data objects in the default data segment, and give you a way (e.g. the /Gt option under Microsoft compilers) to configure the threshold for ``small.''

 91 views