You are on page 1of 26

mQ1.

#include <stdio.h>
struct sample
{
int a = 0;
    char b = 'A';
    float c = 10.5;
};
int main()
{
    struct sample s;
    printf("%d, %c, %f", s.a, s.b, s.c);
    return 0;
}
Output:- Compiler Error
Explanation:- We can only declare members inside the structure, initialization of
member with declaration is not allowed in structure declaration.
(when a datatype is declared, no memory is allocated for it.
Memory is allocated only when variables are created.)

Q2.
#include <stdio.h>
int main()
{
    typedef struct tag
{
        char str[10];
        int a;
    } har;
  
    har h1, h2 = { "IHelp", 10 };
    h1 = h2;
    h1.str[1] = 'h';
    printf("%s, %d", h1.str, h1.a);
    return 0;
}
Output:- Ihelp, 10
Explanation:-  It is possible to copy one structure variable into another like h1 =
h2. Hence value of h2. str is assigned to h1.str.

Q2. What is designated Initialization?


1.) Designated Initialization allows structure members to be initialized in any
order.
2.) It has been introduced in C99
3.) This feature is not available in C++ and works only in C.

#include<stdio.h>
  
struct Point
{
   int x, y, z;
};
  
int main()
{
      struct Point p1 = {.y = 0, .z = 1, .x = 2};// Examples of initialization using
designated initialization
  struct Point p2 = {.x = 20};
   printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z); // x = 2 , y = 0, z = 1
    printf ("x = %d", p2.x); // x = 20
    return 0;
}

Q4. Limitations of C structures


  The C structure does not allow the struct data type to be treated like
built-in data types:
  We cannot use operators like +,-,/,*,= = etc. on Structure variables but
= operator can be used to copy one structure to another
  No Data Hiding: C Structures do not permit data hiding. Structure
members can be accessed by any function, anywhere in the scope of the
Structure.
  Functions inside Structure: C structures do not permit functions inside
Structure
  Static Members: C Structures cannot have static members inside their
body
  Access Modifiers: C Programming language do not support access
modifiers. So they cannot be used in C Structures.
  Construction creation in Structure: Structures in C cannot have
constructor inside Structures.

struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4.0 ;
n2.x=3.0 ;
n3=n1+n2; //Invalid Operation
return 0;
}

Q5. Concept on bit-fields in C


1.) In C, we can specify size (in bits) of structure and union members. The idea is
to use memory efficiently when we know that the value of a field or group of
fields will never exceed a limit or is withing a small range.

2.) The declaration of a bit-field has the following form inside a structure −
struct
{
type [member_name] : width ;
};
 Type = An integral type that determines how a bit-field's value is
interpreted.
The type may be int/short/long/char , signed int/short/long/char, or
unsigned int/short/long/char.
 Member_name = name of the bit field
 Width = The number of bits in the bit-field. The width must be less than or
equal to the bit width of the specified type. (eg. For unsigned int width <=
32)

3.)
// A structure without forced
struct struct alignment
{ { struct test1 {
    unsigned int x : 5;
unsigned int w; unsigned int w : 1;     unsigned int y : 8;
unsigned int h; unsigned int h : 1; };
} status; } status;   
// A structure with forced
alignment
struct test2 {
    unsigned int x : 5;
    unsigned int : 0;
    unsigned int y : 8;
};
  
int main()
{
    printf("Size of test1 =
%lu \n", sizeof(struct
test1));
    printf("Size of test1 =
%lu \n", sizeof(struct
test2);
return 0;
}
This structure 1.) The above structure 1.) A special unnamed bit field
requires 8 bytes requires 4 bytes of of size 0 is used to force
of memory space memory space for status alignment on next boundary.
variable, but only 2 bits
will be used to store the 2.) Output :-
values. Size of test1 = 4
Size of test2 = 8
2.) If you will use up to 32
variables each one with a
width of 1 bit, then also
the structure will use 4
bytes. However as soon as
you have 33 variables, it
will allocate the next slot
of the memory and it will
start using 8 bytes

4.) We cannot have pointers to bit field members as they may not start at a byte
boundary (i.e We cannot get the adress of bit field)
struct test
{
    unsigned int x : 5;
    unsigned int y : 5;
    unsigned int z;
};
int main()
{
     Struct test t;
     printf("Address of t.x is %p", &t.x); //Cannot get the adress of bit field x
printf("Address of t.y is %p", &t.y); //Cannot get the adress of bit field y
     printf("Address of t.z is %p", &t.z); //We can get adressof z as it is not a bit field
    return 0;
}

5.)  In C++, although we can have static members in a structure/class, but bit
fields cannot be static. (C doesn’t allow static members in structure)
struct test
{
    static unsigned int x : 5; //Error :- static member 'x' cannot be a bit-field
};
int main()
{
return 0;
}

6.) Array of bit fields is not allowed.


struct test
{
unsigned int x[10] : 5; // Error:-bit-field 'x' has invalid type
};

int main()
{}

7.) The type of a bit-field shoud be a integral type and not float or double
struct test
{
unsigned char x : 7;
float y : 3;//Error:- bit field y has invalid type
unsigned int z : 7;
};
int main()
{
struct test t;
}

8.) It is implementation defined to assign an out-of-range value to a bit field


member.
struct
{
unsigned int age : 3;//Range :- 0 to (2^3 - 1 ) = 0 to 7
} Age;

int main( )
{

Age.age = 4;//Declared within the range


printf( "Age.age = %d\n", Age.age );//4
Age.age = 7;//Declared within range
printf( "Age.age : %d\n", Age.age );//7
Age.age = 8;//Declared outside the range
printf( "Age.age : %d\n", Age.age );//Will print any vaue b/w 0 and 7 and never 8
}

Q5. Basic Concept of Unions

1.) A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many members,
but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose

Q1. Storage classes in C


1.) Storage Classes are used to describe the features of a variable/function.
2.) These features basically include the scope, visibility and life-time which help
us to trace the existence of a particular variable during the runtime of a program.
3.) To specify the storage class for a variable, the following syntax is to be
followed: storage_class var_data_type var_name;
4.) C language uses 4 storage classes

Q2. Understanding extern keyword for function in C


1.) when a function is declared or defined, the extern keyword is implicitly
assumed.
2.) When we write int foo(int arg1, char arg2) . The compiler treats it as: extern
int foo(int arg1, char arg2);
3.) Since the extern keyword extends the the function’s visibility to the whole
program, the function can be used (called) anywhere in any of the files of the
whole program, provided those files contain a declaration of the function.

Q3. Understanding extern keyword for variables in C


1.) extern int var; Here, an integer type variable called var has been declared (it
hasn’t been defined yet, so no memory allocation for var so
far). And we can do this declaration as many times as we
want.
2.) int var; Here an integer type variable called var has been both
declared and defined . Since this is a definition, the memory
for var is also allocated
3.)  When we declared/defined a function, we saw that the extern keyword was
present implicitly.
4.) But this isn’t the case with variables. If it were, memory would never be
allocated for them. Therefore, we need to include the extern keyword
explicitly when we want to declare variables without defining them
5.)  when an extern variable is declared with initialization in the same line , it is
taken as the definition of the variable as well.
6.) Also, as the extern keyword extends the visibility to the whole program, by
using the extern keyword with a variable, we can use the variable anywhere
in the program 

extern int extern int #include extern int var = int var;
var; var; "somefile.h 0; int main(void)
int int " int main(void) {
main(void) main(void) extern int {    var = 10;
{ { var;  var = 10;    return 0;
  return 0;   var = 10; int  printf("%d",var) }
}   return 0; main(void) ; // 10
} { }
 var = 10;
 return 0;
}

This This var is an extern variab This program


program program declared le is declared compiles
compiles throws an but not with successfully. var 
successfull error in defined initialization in is defined (and
y. compilation anywhere the same line , it declared
Here var is because var  Assuming is taken as the implicitly)
declared is declared that definition of the globally.
only. but not somefile.h variable as well
Notice var defined contains
is never anywhere. the
used so no Essentially, definition
problems the var isn’t of var, this
arise. allocated program
any will
memory. compile
And the successfull
program is y.
trying to
change the
value to 10
of a variable
that doesn’t
exist at all.

Q. Predict The output


#include <stdio.h> #include <stdio.h>
int var = 20; int main()
int main() {
{     int var = var;
    int var = var;     printf("%d ", var);
    printf("%d ", var);     return 0;
    return 0; }
}

Output:- Garbage Value Output:- Garbage Value


1.)  First var is declared, then value is assigned to
it.
2.) As soon as var is declared as a local variable,
it hides the global variable var.

Q4. Understanding register keyword in C


1.) register variables which have the same functionality as that of the auto
variables.
2.) The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available. 
3.) This makes the use of register variables to be much faster than that of the
variables stored in the memory during the runtime of the program.
4.) If a free register is not available, these are then stored in the RAM memory
only
5.) Usually few variables which are to be accessed very frequently in a program
are declared with the register keyword which improves the running time of the
program. 
6.) There is no limit on number of register variables in a C program, but the point
is compiler may put some variables in register and some not.

int main() int main()


{ {
    register int i = 10;     int i = 10;
    int* a = &i;     register int* a = &
    printf("%d", *a);     printf("%d", *a);
} }

1.) If you use & operator with a register variable then compiler may give 1.) register keywor
an error or warning variables. 
2.)  when we say a variable is a register, it may be stored in a register 2.) obviously, a reg
instead of memory  address of a me
3.) accessing address of a register is invalid. (in fact it is a sin) 3.) but we should n
adress of the re
Error Compiles Fine

Q5. Static functions in C


1.) In C, functions are global by default….bcoz compiler implicitly puts extern
keyword before each function
2.) The “static” keyword before a function name makes it static.
3.) Unlike global functions in C, access to static functions is restricted to the file
where they are declared
4.) Therefore, when we want to restrict access to functions, we make them
static. 
5.) Another reason for making functions static can be reuse of the same function
name in other files.

/* Inside file1.c */  Now, if we compile the above code with


static void fun1(void) command “gcc file2.c file1.c”, we get the
{ error “undefined reference to `fun1’” . This is
   puts("fun1 called"); because fun1() is declared static  in file1.c and
} cannot be used in file2.c.

/* Iinside file2.c  */ 


int main(void)
{
   fun1(); 
}

Q6. Interesting facts on static variables in C


Q7. Initialization of static and global variables in C
1.)
Q8. Can global variables be redeclared in C
1.) C allows a global variable to be declared again when first declaration doesn’t
initialize the variable. (C++ doesn’t )
2.) C/C++ does not allow a local variable to be declared again even if the first
declaration doesn’t initialize the variable.

int main() int x; int x = 5;


{ int x = 5; int x = 10;
    int x;      
    int x = 5; int main() int main()
    printf("%d", x); { {
    return 0;     printf("%d", x);    printf("%d", x);
}    return 0;     return 0;
} }

1. compilation fails in 1.) compilation fails in C+ 1.) Compilation fails in


c/c++ + c/c++
2.) compilation successful
in C

Q. typedef in C/C++

Q. typedef vs #define in C/C++


1.) typedef interpretation is performed by the compiler where
#define statements are processed by the preprocessor.

2.) #define should not be terminated with a semicolon


typedef should be terminated with semicolon.

3.) typedef is limited to giving symbolic names to data types only,


 #define can be used to define an alias for values as well, (e.g., you can define
1 as ONE, 3.14 as PI, etc….)

4.) typedef follows the scope rule which means if a new type is defined in a scope
(inside a function), then the new type name will only be visible till the scope is
there.
 In case of #define, when preprocessor encounters #define, it replaces all the
occurrences, after that (No scope rule is followed).

#include <stdio.h> typedef unsigned typedef struct BookDetails


typedef char* ptr; char Ninja; {
#define PTR char*    char title[50];
int main() int main() char author[50];
{ { int id;
ptr a, b, c;     Ninja b1, b2; } Book;
PTR x, y, z;     b1 = 'c';
printf("sizeof a:     cout << " " << int main( )
%u\n" ,sizeof(a) );//4 b1; //c {
printf("sizeof b:     return 0;
%u\n" ,sizeof(b) );//4 } Book b;//struct
printf("sizeof c: BookDetails b;
%u\n" ,sizeof(c) );//4
strcpy( b.title,
printf("sizeof x:
"Pakistan");
%u\n" ,sizeof(x) );//4
strcpy( b.author, "Ali
printf("sizeof y:
Baksh");
%u\n" ,sizeof(y) );//1
b.id = 64;
printf("sizeof z:
%u\n" ,sizeof(z) );//1 printf( "Book title :
return 0; %s\n", b.title);//Pakistan
} printf( "Book author :
%s\n", b.author);//Ali
Baksh
printf( "Book book_id :
%d\n", b.id);//64

return 0;
}
1.) typedef char* ptr; 1.) typedef 1.) Here Book is an alias
ptr a,b,c ; data_type to the datatype struct
 char *a,*b,*c; alias_name BookDetails
2.) typedef is used
2.) #define PTR char* to define an alias
PTR x,y,z; for a datatype
 char* x,y,z;  char 3.) Like in above
*x,y,z example Ninja is an
alias to unsigned
3.) This example char...i.e
demonstrates the Instead of writing
importance of unsigned char
typedef over #define b1,b2…we can write
for data types Ninja b1,b2;

4.) C/C++ allows you


to define explicitly
new data type
names by using
the keyword
typedef

5.)  Using typedef


does not actually
create a new data
class, rather it
defines a name for
an existing type
Q2 . Dynamically allocating 2D array in C

1) Using an array of 2) Using pointer to a pointer


pointers
int main() int main()
{ {
int r = 3, c = 4, i, j, int r = 3, c = 4, i, j, count;
count;
int **arr = (int **)malloc(r *
int *arr[r]; //Create an sizeof(int *));
array of pointers for (i=0; i<r; i++)
for (i=0; i<r; i++) {
{ arr[i] = (int *)malloc(c *
arr[i] = (int sizeof(int));
*)malloc(c * }
sizeof(int)); //
Dynamically allocate 2D count = 0;
aray for (i = 0; i < r; i++)
} {
for (j = 0; j < c; j++)
count = 0;
arr[i][j] = ++count;
for (i = 0; i < r; i++)
}
{
for (j = 0; j < c; j++)
for (i = 0; i < r; i++)
arr[i][j] = ++count;
{
}
for (j = 0; j < c; j++)
for (i = 0; i < r; i++) {
{ printf("%d\t",arr[i][j]);
for (j = 0; j < c; j++) }
{ printf("\n");
printf("%d\t", arr[i] }
[j]);
} printf("\n%d ",**arr+2);//3
printf("\n"); printf("\n%d",(**arr + (1*c) +
} 0));//5
} }
1.) Create an array of 1.) We can create an array of
pointers of size r.  pointers also dynamically using
2.) After creating an array a double pointer. 
of pointers, 2.) we have an array pointers
we can dynamically allocated dynamically, we can
allocate memory for dynamically allocate memory
every row. and for every row like method 1
3.) **arr + n =arr[n] = considering it
as a 1D array stored in row
major order
4.) (**arr + (i*c) + j ) = arr[i][j] =
Common sense

Q3. String as Character pointer vs String as character array


char *str  =  "geek";   int ma
printf("%s",str); //geeks {
str = "Ali" ; //Yes you can make str to point to something else cha
printf("\n%s",str); //Ali *(st
str++;
printf("\n%s",str);//li str =
str = str+1;
printf("\n%s",str);//i
*(str+2) = 'u'; //No you cant modify the content of str prin
printf("%s",str); //No Ouput
}
1.) str is stored in the stack section (read-write-memory) of the memory 1.) str
But geek is stored in the read-only-location ( code segment )(or data segment)
2.) You can make str to point to something else 2.) We
3.) But you cant modify the content of the String represented by str (In ot
4.) str is a pointer variable
5.) str and &str are not same 3.) Bu
6.) sizeof(str) = 4 in
7.) Pointer arithmetic allowed (i.e str = str+i) , 4.) str
5.) str
6.) siz
7.) Po

char *p = "geeks"; char p1[] = "geeks";


char p1[]="Ali"; char p2[10] ;
printf("p = %s\n",p);//geeks p2 = p1;
char *q;
q = p;
printf("\n q = %s ",q); //geeks
q = p1;
printf("\n q = %s ",q);//Ali
*(q+2) = 'u';/*You can change the
content represented by q now
bcoz now bcoz q now
stores the base adress of "Ali"
and not explicitly assigned
any string literal directly*/

printf("\n q = %s ",q);//Alu

1.) Here q stores the base adress of


string literal "geeks" first, then stores the
base adress of "Ali" but here "Ali" and
"geeks" are not stored in read-only-
segment or anything like that

Q. Predict the output


char c[] = "GEEK2018"; char c[] = "GATE2011";
char *p =c; char *p =c;
printf("%c,%c", *p,*(p+p[3]-p[1]));//G,1 printf("%s", p + p[3] - p[1]) ;// 2011
1) *(p+p[3]-p[1]) = *(p+75-69)  = *(p+6) = 1 1) As p is a pointer of type character, using
2) p + p[3] – p[1] = p + 69 – 65 (Using Ascii

2) Now, p + 4 will point to 2, the string sta


printed which is 2011.

Q1. <ctype.h> / <cctype> in C/C++

1.) As string.h header file contains inbuilt functions to handle Strings in C/C++


2.) ctype.h/<cctype> contains inbuilt functions to handle characters in C/C++
respectively.
3.) All the functions accepts int as a parameter, whose value must be EOF(-1) or
representable as an unsigned char
4.) All the functions return non-zero (true) if the argument c satisfies the
condition described, and zero(false) if not.

int isalnum (int c) This function checks whether the passed character is alphanumeric
int isalpha (int c) This function checks whether the passed character is alphabetic.
int isdigit(int c) This function checks whether the passed character is decimal digit
int isxdigit(int c) This function checks whether the passed character is a hexadecima
int islower(int c) This function checks whether the passed character is lowercase lett
int isupper(int c) This function checks whether the passed character is uppercase lett
int isspace(int c) This function checks whether the passed character is white-space.
int isblank(int c) This function checks whether the passed character is blank
int ispunct(int c) This function checks whether the passed character is a punctuation
int isgraph(int c) This function checks whether the passed character has graphical re
locale.
int iscntrl(int c) This function checks whether the passed character is a control cha
int tolower(int c) This function converts uppercase character c to lowercase.
int toupper(int c) This function converts lowercase character c to uppercase.
int isprint(int c) This function checks whether the passed character is a printable ch

5.) Characters are of two types:


1. Printable Characters: The characters that are displayed on the terminal.
2. Control Characters: The characters that are initiated to perform a specific
operation.

Q2. Variable Length arguments in C functions ( stdarg.h header file )


1.) Variable length argument is a feature that allows a function to receive any
number of arguments
2.) A function of variable arguments is defined with the ellipsis (,...) at the end of
the parameter list. Eg. int min(arg_count , …)
3.) For practical example see Fun and Tricks
4.) These Functions are defined in stdarg.h header file

void va_start(va_list ap, arg_count) 1.) This macro initializes ap variable to be used with
2.) The arg_count  is the last known fixed argumen
type va_arg (va_list ap, type) 1.) This macro retrieves the next argument in the p
2.) type = type of arguments passed for ellipsis
void va_end (va_list ap) 1.) This macro allows a function with variable argum
2.) If va_end is not called before returning from th
va_list 1.) Defines a variable argument list of type type

Q3. File handling functions in C


int fprintf(FILE *stream, const
char *format, ...)

int fgetc(FILE *stream) 1.) This function gets the next character (an
unsigned char) from the specified stream and
advances the position indicator for the
stream.
2.) This function returns the character read as an
unsigned char cast to an int or EOF on end of
file or error.
3.) stream − This is the pointer to a FILE object
that identifies the stream on which
the operation is to be performed.
int getc(FILE *stream) 1.) This function gets the next character (an
unsigned char) from the specified stream and
advances the position indicator for the
stream.

2.) This function returns the character read as an


unsigned char cast to an int or EOF on end of
file or error.
3.) stream − This is the pointer to a FILE object
that identifies the stream on which
the operation is to be performed.
int fputc (int ch, FILE 1.) This function writes a character (an unsigned
*stream) char) specified by the argument char to the
specified stream and advances the position
indicator for the stream.
2.) ch − This is the character to be written. This is
passed as its int promotion.
3.) stream − This is the pointer to a FILE object
that identifies the stream where the
character is to be written.
4.) To write to the console we write
putc(ch,stdout)
5.) If there are no errors, the same character
that has been written is returned.
6.) If an error occurs, EOF(-1) is returned
int putc (int ch, FILE *stream) 1.) This function writes a character (an unsigned
char) specified by the argument char to the
specified stream and advances the position
indicator for the stream.
2.) ch − This is the character to be written. This is
passed as its int promotion.
3.) stream − This is the pointer to a FILE object
that identifies the stream where the character is
to be written.
4.) To write to the console we write
putc(ch,stdout)
5.) If there are no errors, the same character
that has been written is returned as an
unsigned char cast to an int
6.) If an error occurs, EOF(-1) is returned

char * fgets(char* str , int 1.) This function  reads a line from the specified
n+1 , FILE *stream) stream and stores it into the string pointed to
by str
1.) It stops when  (n) characters are read,or
newline character (\n) is read, or the end-of-file
(EOF) is reached, whichever comes first.

2.) str − This is the pointer to an array of chars


where the string read is stored.
3.) stream − This is the pointer to a FILE object
that identifies the stream where characters are
read from.
4.) n+1 = This is the maximum number of
characters to be read (including the final null-
character)
= To read n characters from the stream

5.) On success, the function returns the same str


parameter
6.) If the EOF is encountered and no characters
have been read, the contents of str remain
unchanged and a NULL pointer is returned.
7.) To read string from standard input stream
write fgets(str , INT_MAX , stdin)

char* gets(char *str) 1.) This function reads a line from stdin and
stores it into the string pointed to by str
2.) It stops when newline character (\n) is read,
or the end-of-file (EOF) is reached, whichever
comes first.

3.) str − This is the pointer to an array of chars


where the C string is stored.
4.) On success, the function returns the same str
parameter
5.) If the EOF is encountered and no characters
have been read, the contents of str remain
unchanged and a NULL pointer is returned.

int fputs(const char* str , FILE 1.) This function writes a string to the specified
* stream) stream but does not include the null character.
2.) str − This is an array containing the null-
terminated sequence of characters to be written
to the specified stream
3.) stream − This is the pointer to a FILE object
that identifies the stream where the string is to
be written.
4.) This function returns a non-negative value, or
else on error it returns EOF.
5.) To write to the standard output stream
stdout write fputs (const char* str , stdout );
int puts(const char *str) 1.) This function writes a string to the stdout
but does not include the null character
2.) str − This is an array containing the null-
terminated sequence of characters to be written
to stdout
3.) This function returns a non-negative value, or
else on error it returns EOF.

int fseek(FILE * stream , long 1.) This function makes the file pointer skip
int offset , int origin ) (offset) no. of characters…i.e current position of
file pointer is the (offset+1)th position
2.) stream − This is the pointer to a FILE object
3.) offset = Indicates how many characters in
the file you want to skip
4.) origin = Pt. from where you want to start
skipping characters using offset
= It has 3 values(macros)
(SEEK_SET , SEEK_END , SEEK_CUR )
5.) SEEK_SET = start of file
6.) SEEK_END = end of file
7.) SEEK_CUR = current position of the file
pointer
long int ftell (FILE * stream) 1.) This function returns the current file position
pointed by the given file pointer stream
2.) stream − This is the pointer to a FILE object
that identifies the stream.
3.) This function returns the current value of the
file position indicator
4.)  If an error occurs, -1L is returned, and the
global variable errno is set to a positive value.
Int remove (const char* 1.) This function deletes the given filename so
filename) that it is no longer accessible.
2.) filename − This is the C string containing the
name of the file to be deleted.
3.) On success, zero is returned. On error, -1 is
returned, and errno is set appropriately.
int rename(const char 1.) This function changes the name of the old file
*old_filename, const char ( old_filename ) to new_filename.
*new_filename) 2.) old_filename − This is the C string containing
the name of the file to be renamed and/or
moved.
3.) new_filename − This is the C string
containing the new name for the file.
4.) On success, zero is returned. On error, -1 is
returned, and errno is set appropriately.

Q. Problem with scanf() when there is fgets()/gets()/scanf() after it

int x; char c; int x;


char str[100]; printf("......Enter q to char str[100];
printf("Enter Value of quit......\n"); printf("Enter Value of
x : "); do x : ");
scanf("%d", &x); //3 { scanf("%d", &x); //3
printf("Enter Value of str printf("Enter a gaetchar();
: ");//4 character\n"); printf("Enter Value of
fgets(str, 100, stdin); //5 scanf("%c", &c); str : ");//4
printf("\n x = %d, str = printf("printed = %c\n", c); fgets(str, 100, stdin); //5
%s", x, str); //6 } printf("\n x = %d, str =
while (c != 'q'); %s", x, str); //6

Enter Value of x : 15 ......Enter q to quit...... char c;


Enter value of str :- Enter a character printf("......Enter q to
x = 15, str = a quit......\n");
printed = a do
Enter a character {
printed = printf("Enter a
character\n");
Enter a character scanf("%c", &c);
b getchar();
printed = b printf("printed =
Enter a character %c\n", c);
printed = }
while (c != 'q');
Enter a character
c
printed = c
Enter a character
printed =

Enter a character
q
printed = q
1.) The problem with 1.) We can notice that above 1.) The above 2
above code is scanf() program prints an extra programs work
in line 3 reads an “Enter a character” absolutely fine
integer and leaves a followed by an extra
newline character in new line
buffer. 2.) This happens because
2.) So fgets() only reads every scanf() leaves a
newline as string in newline character in
line 5 buffer that is read by
3.) And then the content next scanf.
of x and str is
printed

1.) We can add a getchar() after scanf() to read an extra newline. [Works Perfect]
2.) We can make scanf() to read a new line by using an extra “\n”,
i.e., scanf(“%d\n”, &x) [Works Stangely] 
3.) In fact scanf(“%d “, &x) also works (Note extra space). [Works Stangely] 
4.) see the mad scanf() for better illustration

Q. fgets( ) vs gets( ) in C

Declaration:- char * fgets(char* str , Declaration:-


int n+1 , FILE *stream)

It is safe to use because it checks the It is not safe to use because it does not
array bound. check the array bound.
It keep on reading until (new line It keep on reading until (new line
character encountered) or (EOF is character encountered) or (EOF is
encountered) or encountered)
(maximum n characters is read )
1.) Suppose we have a character array 1.) Suppose we have a character array of
of 15 characters and input is greater 15 characters and input is greater than
than 15 characters 15 characters
2.) fgets() will read only 14 characters 2.) gets() will read all these characters
and store them into variable. and store them into variable.
3.) compiler will never return buffer 3.) Since, gets() do not check the
overflow error. maximum limit of input characters,
so at any time compiler may return
buffer overflow error.

Q. sprintf , snprintf , sscanf ,


1) int sprintf(char *buffer, const char *format, ...) 1.) sprintf stands for “St
2) int sprintf(char* buffer , "format specifiers",…..) 2.) Instead of printing o
sprintf
3.) It sends formatted o
4.) If successful, the tot
excluding the null-ch
5.) otherwise a negative
6.) format =

1.) int sscanf(const char* buffer, const char *format, ...) 1.) This function  reads
2.) int sscanf(const char* buffer, "Format Specifier", ...) 2.) On success, the func
the String buffer
3.) In case of an input fa
returned.

1) int snprintf(char *buffer, size_t n, const char *format, ...); 1.) Instead of printing o
2) int snprintf(char *buffer, size_t n,"Format specifiers", ...); snprintf
3) defined in <stdio.h> header file 2.) It sends formatted ou
3.) n : It is the maximum
buffer.
4.) It returns the total nu
buffer as mentione
character
5.) But it sends only n b
6.) returns negative num

1.) int wprintf (const wchar_t* format, ...); 1.) The wprintf() functio
2.) If successful, the wp
stdout
3.) On failure it returns

You might also like