Documente Academic
Documente Profesional
Documente Cultură
1.#include <stdio.h>
void main()
{
int x = 5;
printf("%d,%d,%d",x,(x<<2),(x>>2));
}
Ans: 5,20,1
2.#include <stdio.h>
void main()
{
char a[]="hello";
char b[]="hai";
a=b;
printf("%s,%s",a,b);
}
ANs : since a is the base address of the array it is a lValue(constant)
which can not be assigned with a value a=b is a error.
3.#include <stdio.h>
void main()
{
char * p = "hello",ch;
ch = *++p;
printf("%c,%s",ch,p);
Ans e,ello
4.#include <stdio.h>
#include <string.h>
#define TOTAL 3
#define MAXNAMELEN 80
struct company
{
char organization[TOTAL][MAXNAMELEN];
};
int main()
{
void nameswap(struct company)
struct company x;
int i;
strcpy(x.organisation[0],"AATT India");
strcpy(x.organisation[1],"AATT Corporation");
strcpy(x.organisation[2],"AATT Limited");
nameswap(x);
for(i=0;i<TOTAL;i++)
printf("\n %s",x.organisation[i]);
return(1);
}
void nameswap(struct company x)
{
char tempname[MAXNAMELEN];
strcpy(tempname,x.organisation[0]);
strcpy(x.organisation[0],x.organisation[1]);
strcpy(x.organisation[1],tempname);
return;
}
5 #inlcude <stdio.h>
#define Stringizer(x) printf(#x)
void main()
{
Stringizer(hello);
}
6. #include <stdio.h>
#define Charizing(x) printf("%d",#@x)
void main()
{
Charizing(a);
}
Ans : 97
7.#include<stdio.h>
#include<string.h>
int main( )
{
char *ptr1,*ptr2;
ptr1 = "Hello AATT";
ptr2 = "Hai";
ptr1= strcat(ptr1,ptr2);
printf("\n Input string %s",ptr1);
return 1;
}
Ans : Enough memory not allocated for concatenation
8.int main( )
{
int x=20,y=35;
x=y++ + x++;
y=++y + ++x;
printf("%d %d",x,y);
return 1;
}
Ans : 57,94
9.int main( )
{
int i,*p;
i=10;
p=&i;
printf("%d",10/*p);
return 1;
}
Ans:Since there is no space between / and * it is taken to be a comment and the output
will not be 10/10 =1 as expected
int main()
{
int a=0;
if(a= 0)
printf("hello");
printf("AATT");
return 0;
}
Ans :AATT
11.Write a function to swap two numbers without using temp .
Ans :
Swap(a,b)
{
a= a+b;
b= a-b;
a= a-b;
}
12.O/p of Following
int main()
{
char a[2];
*a[0]=7;
*a[1]=5;
printf("%d",&a[1]-a);
}
13.
int main()
{
char a[]="hellow";
char *b="hellow";
char c[5]="hellow";
printf("%s %s %s ",a,b,c);
printf(" %d,%d,%d",sizeof(a),sizeof(b),sizeof(c));
}
Ans :5
int main()
{
Prime(56);
}
p =(char *) malloc(len+1);
while(i<= len)
{
}
p[len] = '\0';
return p;
}
17. Output of
int main()
{
printf("%d%x\n",0x2,12);
ans :2C
18.swap two var without Temp and Arithmetic ops
Ans:
swap(a,b)
{
a=a^b;
b=a^b;
a=a^b;
}
19.int main()
{
int a[5],*p;
for(p=a;p<&a[5];p++)
{
*p=p-a;
printf("%d\n",*p);
}
Ans : 0,1,2,3,4
}
void swap (char *x,char *y)
{
char *t;
t=x;
x=y;
y=t;
printf("(%s, %s)-",x,y);
}
a).(New,Dictionary)-(New,Dictionary)
b).(Dictionary,New)-(New,Dictionary)
c).(New,Dictionary)-(Dictionary,New)
d).(Dictionary,New)-(Dictionary,New)
e).None of the above
Ans :c
23.
main()
{
main();
printf("InMain \t");
}
24.
main()
{
printf("InMain \t");
main();
}
Ans ???
26.int x ;
int intg()
{
return x+=4;
}
int diff()
{
return x/=4;
}
main()
{
x = intg()+diff();
printf("%d",x);
}
Ans 5
27.
int x;
main()
{
int j =2;
printf("%d",fun(j));
}
fun(int x)
{
x++,++x;
return x++;
}
Ans 4
28.
main()
{
static char *s[] = {"ice","green","cone","please"};
static char **ptr[] = {s+3,s+2,s+1,s};
char ***p = ptr;
printf("%s",**++p);
printf("\n%s",*--*++p +3);
printf("\n%s",*p[-2] +3);
printf("\n%s" , p[-1][-1] +1);
}
Ans :
cone
ase
reen
29.
main()
{
float **a;
int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%f",&a[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("%f",a[i][j]);
}
Ans :
Memory not allocated for a
30.
main()
{
printf("%d",sizeof("1234"));
printf("%d",sizeof(1));
printf("%d",sizeof(1.1));
}
Ans 548
31.
main()
{
int *x;
int y[3] = {10,20,30};
x=y;
printf("%d",++*x);
printf("\n%d",++*x++);
}
Ans 11,12
32.
int main()
{
char s[] = "Get organised";
printf("%s",&s[2]);
printf("\n %s",s);
printf("\n %s",&s);
printf("\n %c",s[2]);
}
Ans:
t organised
Get organised
Get organised
t
33.
Ans : i) specifies that k is a pointer to integer constant , the k can be changed to point to
another int value,but the value pointed by k can not be changed.
ii) specifies that k is a constant pointer to an integer , the value pointed to by the k can
be changed ,but the k can not be made to point to another integer .
34 .
main()
{
int const *f;
int x = 10;
f = & x;
*f = 15
printf("%d",x);
}
Ans :
f cannot change the value of the pointed memory.
35.
main()
{
int const *f;
int x = 10,y =15;
f = & x;
printf("%d",*f);
f = & y;
printf("%d",*f);
Ans :
f cannot be assigned different addresses because it is a constant pointer.
36.
main()
{
int a[6]={0,1,2,3,4,5};
int (*p)[3];
p=a;
*p[1] = 5;
printf("%d",a[1]);
}
37.
main()
{
char i ;
for(i=0;i<256;i++)
printf("%d",i);
}
38.
main()
{
char s[]="Hello World";
s++;
printf("%s",s);
}
39.main()
{
char *s="Hello World";
s++;
printf("%s",s);
}
40.
main()
{
char *s;
s = "Hello World";
printf("%s",s);
}
41.
main()
{
int *s;
s = "Hello World";
printf("%s",s);
}
42.
main()
{
char s[] = "Hello";
printf("%s" , s[3]);
}
Ans : %s needs an address whereas s[3] returns a content in the location s+3.
43.
main()
{
extern int a;
printf("%d",a);
}
44.
main()
{
inti=-3,j=2,k=0,m;
m=++i&&++j||++k;
printf("\n %d %d %d %d",i,j,k,m);
}
Ans : 2 3 0 1
45.
main()
{
int a,b;
a=sumdig(123);
b=sumdig(123);
printf("%d %d",a,b);
}
sumdig(int n)
{
static int s=0;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
s=s+d;
sumdig(n);
}
else return(s);
}
Ans :6,12
46.
Ans :27,6
47.
main()
{
char *p,*f();
p=f();
printf("f() returns:%s\n",p);
}
char *f()
{
char result[80];
strcpy(result,"anything will do");
return (result);
}
Ans : f() returns :
48.
main()
{
short int *p,*q;
p=(short int *)1000;
q=(short int *)2000;
printf("%d",(q-p));
}
49
main()
{
char a =0xAA ;
int b ;
b = (int) a ;
b = b >> 4 ;
printf("%x",b);
Ans : ffffffaa
50.
.main()
{
char *p = "hello world!";
p[0] = 'H';
printf("%s",p);
}
Ans : Run time error .
51.
main()
{
char *p ;
char s[20] = "Hello world!";
strcpy(p,s);
printf("%s",p);
}
52.
main()
{
char *p ;
char s[20] = "Hello world!";
p = (char *)malloc(20);
strcpy(p,s);
printf("%s",p);
}
53.
main()
{
int a=10,b;
a>= 5 ? b=100 : b=200;
printf("\n%d",b);
}
54.
main()
{
int a=10,b;
a>5 ? a++ : a++;
printf("\n%d",a);
}
Ans : 11
55.
Given a piece of code
int x[10];
int *ab;
ab=x;
To access the 6th element of the array which of the following is incorrect?
(A) *(x+5) (B) x[5] (C) ab[5] (D) *(*ab+5} .
Ans : d
56.
Consider the following program
main()
{
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}
The value of b[-1] is
(A) 1 (B) 3 (C) -6 (D) none
Ans : b
57.
What does the following program print?
#include <stio.h>
int sum,count;
void main(void)
{
for(count=5;sum+=--count;)
printf("%d",sum);
}
a. The pgm goes to an infinite loop b. Prints 4791010974 c. Prints 4791001974
d. Prints 5802112085 e. Not sure
Ans: a
58.
#include <stdio.h>
void main(void)
{
int i;
for(i=2;i<=7;i++)
printf("%5d",fno());
}
fno()
{
staticintf1=1,f2=1,f3;
return(f3=f1+f2,f1=f2,f2=f3);
}
a. produce syntax errors b. 2 3 5 8 13 21 will be displayed c. 2 2 2 2 2 2 will be
displayed
d. none of the above e. Not sure
Ans : b
59.
#include <stdio.h>
void main (void)
{
int x;
x = 0;
if (x=0)
printf ("Value of x is 0");
else
printf ("Value of x is not 0");
}
a. print value of x is 0 b. print value of x is not 0 c. does not print anything on the screen
d. there is a syntax error in the if statement e. Not sure
Ans : a
60.
void main (void)
{
char arr[100] = {"Welcome to Mistral"};
foo (arr);
}
foo (char *x)
{
printf ("%d\t",strlen (x));
printf ("%d\t",sizeof(x));
return0;
}
a. 100 100 b. 18 100 c. 18 18 d. 18 2 e. Not sure
Ans : 18,100
61.
#include <stdio.h>
display()
{
printf ("\n Hello World");
return 0;
}
void main (void)
{
int (* func_ptr) ();
func_ptr = display;
printf ("\n %u",func_ptr);
(* func_ptr) ();
}
Ans : it prints the address of the function display and prints Hello World on the screen
62.
#include <stdio.h>
void main (void)
{
int i = 0;
char ch = 'A';
do
putchar (ch);
while(i++ < 5 || ++ch <= 'F');
}
Ans : AAAAAABCDEF
* MORE C PROGRAMS *
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c;
char q;
printf("Enter the values for the number \n");
scanf("%d%*[-/]%d%*[-/]%d",&a,&b,&c);
printf("%d %d %d",a,b,c);
getch();
}
/*assignment supression character*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%*d\n",12,34);
printf("%.*f\n",4,23.22);
getch();
}
/*indirect width specifier and indirect precision specifier */
#include<stdio.h>
#include<conio.h>
void main()
{
int a=4,b=-3;
clrscr();
printf("%d",a%b);
getch();
}
/*the sign of the remainder is the sign of the numerator */
#include<stdio.h>
#include<conio.h>
void main()
{
int p,m,n,q;
printf("Enter the number of lines ");
scanf("%d",&n);
clrscr();
for(p=1;p<=n;p++)
{
for(q=1;q<=n-p;q++)
printf(" ");
m=p;
for(q=1;q<=p;q++)
printf("%4d",m++);
m=m-2;
for(q=1;q<p;q++)
printf("%4d",m--);
printf("\n\n");
}
printf("\n");
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void prin(const char *start ,...)
{
va_list arg_list;
int i;
char *s;
printf("%s \n",start);
va_start(arg_list,start);
while(s)
{
s=va_arg(arg_list,char *);
i=va_arg(arg_list,int);
if(s)
printf("%s %d\n",s,i);
}
va_end(va_list);
}
void main()
{
clrscr();
prin("dhankumar ","kumar", 1000 ,"times", 83," dsj289jk","38",NULL);
getch();
}
#include<stdio.h>
#include<conio.h>
void tower(unsigned int ,char,char,char);
void main()
{
unsigned int v;
char s='L',i='M',d='R';
clrscr();
printf("Enter the no of disks");
scanf("%u",&v);
printf("The Towers of hanoi problem for %u disks\n",v);
tower(v,s,i,d);
printf("\n");
getch();
}
void tower (unsigned int v,char s,char i,char d)
{
if(v!=0)
{
tower(v-1,s,d,i);
printf("Move %d disk from %c to %c\n",v,s,d);
tower(v-1,i,s,d);
}
}
#include<stdio.h>
#include<conio.h>
void main(int argc,char **argv,char **env)
{
int i=0;
clrscr();
printf("the no of commandline arguments %d\n",argc);
printf("The commandline arguments are as follows\n");
for(i=0;i<argc;i++)
printf("%s\n",argv[i]);
printf("The environmemt variables are as follows\n");
for(i=0;i<argc;i++)
printf("%s\n",env[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int **p;
int i,j,m,n;
printf("Enter the dimension of the 2d array\n");
scanf("%d%d",&m,&n);
p=(int **)malloc(m*sizeof(int));
for(i=0;i<m;i++)
p[i]=(int *)malloc(n*sizeof(int ));
clrscr();
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter a num:");
scanf("%d",&p[i][j]);
}
}
clrscr();
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\n",p[i][j]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
static char s[]="dhankumar";
clrscr();
printf("%s",s+3);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
char far * p;
clrscr();
p=(char far *)MK_FP(0xB800,0x0000);
printf("%c\n",*p);
unsigned int of,se;
of=FP_OFF(p);
printf("%#x\n",of);
se=FP_SEG(p);
printf("%#x\n",se);
getch();
}
#include<stdio.h>
#include<conio.h>
void strcp(char *,char *);
void main()
{
char *s1,*s2;
clrscr();
printf("Enter the source sring\n");
gets(s1);
printf("Enter the destination string\n");
gets(s2);
strcp(s1,s2);
printf("The copied string is %s",s1);
getch();
}
void strcp(char *s,char *d)
{
while(*s++= *d++);
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
int strcm(char *,char *);
void main()
{
char *s1="kumar",*s2="ra";
clrscr();
printf("%d\n",strcmp(s1,s2));
printf("%d",strcm(s1,s2));
getch();
}
int strcm(char *s,char *d)
{
while((*s==*d)&&(*s!='\0')&&(*d!='\0'))
{
s++;d++;
}
return(*s-*d);
}
#include<stdio.h>
#include<conio.h>
int fun(int x)
{
return (x*x);
}
void main()
{
int (*p)(int);
p=fun;
clrscr();
printf("%d",p(14));
getch();
}
#include<stdio.h>
#include<conio.h>
int f(int x)
{
return (x*x);
}
int fun(int x,int (*p)(int x))
{
return (x+p(x));
}
void main()
{
int (*r)(int x,int (*w)(int x));
int (*p)(int x);
r=fun;
p=f;
clrscr();
printf("%d",r(3,p));
getch();
}
#include<stdio.h>
#include<conio.h>
int b(int ,int );
int s(int ,int ,int (*p)(int x,int y));
int b(int x,int y)
{
return (x>y?x:y);
}
int s(int x1,int y1,int (*p)(int x,int y))
{
return (p(x1,y1));
}
void main()
{
int (*p)(int x,int y);
p=b;
clrscr();
printf("%d",s(21,3,p));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d\n",stdin);
printf("%d\n",stdout);
printf("%d\n",stdprn);
printf("%d\n",stdaux);
printf("%d\n",stderr);
getch();
}
/*stream is actually a pointer to the FILE structure .The above mentioned
stream are predefined streams and they are opened whenever a C program
executes */
#include<stdio.h>
#include<conio.h>
void main()
{
char i[23];
clrscr();
fputs("Enter a string :\n",stdout);
fgets(i,23,stdin);
// fprintf(stdout,"%s\n",i);
fputs(i,stdout);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int n;
char s[23];
FILE *fp;
clrscr();
if((fp=fopen("kumar","w"))==0)
{
printf("File cannot be opened \n");
exit(1);
}
printf("Enter the name and age \n");
while((scanf("%s %d",s,&n))!=EOF)
fprintf(fp,"%s %d\n",s,n);
fclose(fp);
printf("output \n");
fp=fopen("kumar","r");
printf("NAME AGE\n");
printf("---------------\n");
while((fscanf(fp,"%s %d",&s,&n))!=EOF)
printf("%s %d\n",s,n);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
int c,co=0;
printf("Enter the character \n");
fp=fopen("kumar1","w");
while((c=getchar())!=EOF)
fputc(c,fp);
fclose(fp);
printf("output\n");
fp=fopen("kumar1","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",(char)c);++co;
}
fclose(fp);
printf("The no of characters present in the file are %d ",co);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
printf("%d\n",abs(-32768));
printf("%d\n",abs(-32769));
getch();
}
#include<stdio.h>
#include<conio.h>
#include<assert.h>
void main()
{
clrscr();
assert(3>3);
printf("finishing of the program");
getch();
}
/*assert checks for the condition if it evaluates to zero then print
the error message to the screen and calls the abort function to abort
the program*/
#include<stdio.h>
#include<conio.h>
void f();
void main()
{
clrscr();
f();
f();
getch();
}
void f()
{
static int a=4;
// a=a*a;
printf("%d\n",a=a*a); //this satement will change the value of the 'a'
}
/*if you put the statement printf("%d",a*a); instead of the above statement
this printf just print the value and did not change the value of the variable
a .hence use the above two lines*/
/*but if you want to increment the variable using the static variable then
you can put the statement a++ int the printf itself*/
/*you can also use the statement printf("%d",a*=a);*/
#include<stdio.h>
#include<conio.h>
void main()
{
char y='A';
char s[]="kumar";
char *p;
// p=&y;
p=s;
clrscr();
printf("%s",p);
getch();
}
#include<stdio.h>
#include<conio.h>
int xor(int ,int);
void main()
{
clrscr();
printf("%d\n",xor(1,0));
printf("%d\n",xor(1,1));
printf("%d\n",xor(0,0));
printf("%d\n",xor(0,1));
getch();
}
int xor(int x,int y)
{
return ((x||y)&&!(x&&y));
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("%d\n",sizeof(i));
printf("%d\n",sizeof i); //note this sizeof is an unary compile operator
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[1][5];
clrscr();
printf("%d\n",sizeof a);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s[]="kumar";
clrscr();
char *p[]={"vijya","kumar"};
printf(s);
printf(p[0]);
getch();
}
/*since printf needs a const char * argument*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *p;
p=malloc(4);
clrscr();
printf("%d",*p);
getch();
}
/*In C void* pointer is automatically converted to the type of the
left hand side of the assignement */
#include<stdio.h>
#include<conio.h>
int substr(char *s1,char *s2);
void main()
{
clrscr();
if(substr("dhankumar is hard","is")!=-1)
printf("The substring is found \n");
else
printf("The substring is not found\n");
getch();
}
int substr(char *s1,char *s2)
{
int i;
char *p1,*p2;
for(i=0;s1[i];i++)
{
p1=&s1[i];
p2=s2;
while(*p2&&*p2++==*p1++)
if(!*p2)
return i;
}
return -1;
}
#include<stdio.h>
#include<conio.h>
int strc(char *,char );
void main()
{
clrscr();
if(strc("dhankumar",'e')!=-1)
printf("The given character is found ");
else
printf("The given character is not found ");
getch();
}
int strc(char *s1,char c)
{
while(*s1&&*s1++!=c);
if(*(--s1)==c)
return 1;
return -1;
}
#include<stdio.h>
#include<conio.h>
struct
{
int a:3;
char s:1;
}ob;
void main()
{
clrscr();
printf("%d",sizeof(ob));
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char b1[100]="hello";
char b2[100]="world";
char *p1=b1+2;
char *p2=b2+3;
clrscr();
strcpy(p1,b2);
strcpy(p2,b1);
printf("%s\n",b1);
printf("%s",b2);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%e\n",0.034);
printf("%e\n",335.5);
printf("%E\n",335.5);
getch();
}
/*note the use of the format specifier the printf function adjusts such that
the output has one whole digit and fractional digits in terms of power of
both positive number and negative number*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
double f;
for(f=1.0;f<1.0e+10;f*=10)
printf("%g \n",f);
getch();
}
/*by using the %g or %G format specifier you can tell the printf function
to use either %f or %e but this cause the printf() to select that
produces the shortest output*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%x\n",10);
printf("%X",10);
getch();
}
/*%x and %X are used to display the specifed number in hexadecimal
number in the lowercase and uppercase */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int p;
printf("%d\n",&p);
printf("%u\n",&p);
printf("%X\n",&p);
printf("%p",&p);
getch();
}
/*display the address in a format compatiblee with the type of addressing
used by the computer */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i;
i=printf("%d\n",i);
printf("%d",i);
getch();
}
/* printf retunrs the no of characters outputed*/
#include<stdio.h>
#include<conio.h>
void main()
{
int p;
clrscr();
printf("kumar%n\n",&p);
printf("%d",p);
getch();
}
/* This is one of the special format specifier availiable in the C language
this makes printf() to load the variable pointed to by its arguments with
a value equal to the number of characters that have been output*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%11.4f\n",123.1234567);
printf("%3.8d\n",1000);
printf("%10.15s\n","this is a simple test");
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
scanf("%d%n",&a,&a);
printf("%d",a);
getch();
}
#include<stdio.h>
#include<conio.h>
main()
{
char *p="kumar";
clrscr();
printf("%c",++*(p++));
getch();
}
/* '++' operator comes after the indirection operator ,hence the increment
is done at the value .here ofcourse 'r' ,but 'r'+1 leads to 's'*/
#include<stdio.h>
#include<conio.h>
main()
{
struct
{
int i;
}*a;
*&a->i=4;
clrscr();
printf("%d",a->i);
getch();
}
#include<stdio.h>
#include<conio.h>
unsigned getbit(unsigned x,int p,int n);
void main()
{
clrscr();
printf("%d",getbit(8,4,3));
getch();
}
unsigned getbit(unsigned x,int p,int n)
{
return (x>>(p+1-n))& ~(~0<<n);
}
#include<stdio.h>
#include<conio.h>
void main()
{
struct kumar
{
int i;
float f;
}*p;
clrscr();
(*p).i=2;
p->f=45.67;
printf("%d %f",*&p->i,(*p).f);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
printf("%6d%c",a[i],(i%10==9) || i==5-1)?'\n':' ');
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b=1;
a=b+2,b+=1,b+=1;
clrscr();
printf("%d %d",a,b);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char s[45];
int c;
clrscr();
printf("Enter your text :");
fp=fopen("r2","w");
while((c=scanf("%s",s))!=-1)
fprintf(fp,"%s\n",s);
fclose(fp);
clrscr();
printf("The content:");
fp=fopen("r2","r");
while(fgets(s,45,fp)!=NULL)
printf("%s",s);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int i,c;float f;
clrscr();
fp=fopen("r2","w");
printf("Enter an integer and float:");
while((c=scanf("%d %f",&i,&f))!=EOF)
fprintf(fp,"%d %f\n",i,f);
fclose(fp);
clrscr();
fp=fopen("r2","r");
printf("Reading from the file\n");
while((c=fscanf(fp,"%d %f",&i,&f))!=EOF)
printf("%d %f\n",i,f);
fclose(fp);
getch();
}
#include<stdio.h>
main()
{
int i=10;
clrscr();
printf("%d",++i++);
printf("%d",++i);
getch();
}
/*lvalue required in the function main */
#include<stdio.h>
#include<conio.h>
void main()
{
char s[]="%d\n";
int i=44;
clrscr();
printf(s,i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int c;
clrscr();
fp=fopen("r3","wb");
printf("Enter the numbers:");
while((c=getchar())!=EOF)
fputc(c,fp);
fclose(fp);
clrscr();
printf("Reading from file:\n");
fp=fopen("r3","rb");
while((c=fgetc(fp))!=EOF)
{
printf("positon%ld ",ftell(fp));
putchar(c);
}
getch();
fclose(fp);
}
#include<stdio.h>
#include<stdlib.h>
#include <fcntl.h>
#include<IO.h>
#include<sys/types.h>
#include<sys/stat.h>
void main(int argc,char *argv[])
{
char bu[512];
int ih,oh,b;
ih=open(argv[1],O_RDONLY|O_BINARY);
if(ih==-1)
{
puts("Cannot open file");
exit(1);
}
oh=open(argv[2],O_CREAT|O_BINARY|O_WRONLY);
if(oh==-1)
{
puts("Cannto open file");
close(ih);
exit(1);
}
while(1)
{
b=read(ih,bu,512);
if(b>0)
write(oh,bu,b);
else
break;
}
close(ih);
close(oh);
}
#include<stdio.h>
#include<conio.h>
struct t
{
int h;
int m;
int s;
};
void up(struct t *);
void di(struct t *);
void de(void );
void main()
{
struct t sy;
sy.h=0;
sy.m=0;
sy.s=0;
clrscr();
for(;;)
{
if(!kbhit())
{
up(&sy);
di(&sy);
}
else
break;
}
clrscr();
printf("The current time is \n");
di(&sy);
getch();
}
void up(struct t *p)
{
p->s++;
if(p->s==60)
{
p->s=0;
p->m++;
}
if(p->m==60)
{
p->m=0;
p->h++;
}
if(p->h==24)
p->h=0;
de();
}
void di(struct t *p)
{
printf("%02d:",p->h);
printf("%02d:",p->m);
printf("%02d\n",p->s);
}
void de()
{
long l;
for(l=0;l<128000;++l);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i=10;
int a=i/++i;
clrscr();
printf("%d %d",a,i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[],char *env[])
{
int i;
clrscr();
printf("The command line arguments are %d\n",argc);
printf("\n");
for(i=0;i<argc;i++)
printf("argv[%d]: %s\n",i,argv[i]);
printf("\n");
for(i=0;env[i];i++)
printf("%s\n",env[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char c[23];
int i=0;
clrscr();
printf("Enter a string :");
while( (c[i++]=getchar())!='\n');
c[--i]='\0';
printf("%s",c);
getch();
}
#include<stdio.h>
typedef char *cp;
void main()
{
const cp p=0;
clrscr();
strcpy(p,"kumara");
printf("%d",*++p);
getch();
}
/*Here the important is the typedef declaration statement .The typedef
statement declares that cp is a char * and in the main() we are declaraing
the variable p as const cp here the typedef works differently from
#define it makes the pointer to be const and not the object*/
#include<stdio.h>
#include<conio.h>
void main()
{
typedef struct
{
int a;
float b;
char *p;
}kumar;
static kumar r;
clrscr();
printf("%d %f %s",r.a,r.b,r.p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
char *s;
void main()
{
strcpy(s,"kumar");
clrscr();
printf("%s",s);
getch();
}
#include<stdio.h>
#include<conio.h>
int i;
void in()
{
i++;
}
void main()
{
for(i=0;i<10;)
in();
clrscr();
printf("%d",i);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<mem.h>
void main()
{
char a[2][4];
int i,j;
memset(a,1,sizeof(a));
clrscr();
for(i=0;i<2;i++)
for(j=0;j<4;j++)
printf("%d\n",a[i][j]);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<mem.h>
void main()
{
int a[23];
int i;
clrscr();
memset(a,1,sizeof(a));
for(i=0;i<23;i++)
printf("%d\n",a[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=4,b;
b=(a,a+4,a+3);
printf("%d",b);
getch();
}
#include<stdio.h>
#include<conio.h>
struct kumar
{
int a;
}c;
void main()
{
struct kumar d;
clrscr();
printf("%d\t %d",c.a,d.a);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
struct kumar
{
int i;
int j;
}*p;
clrscr();
printf("%u\n",p);
printf("%u",++p);
getch();
}
#include<stdio.h>
#include<conio.h>
int i;
void in(int i)
{
i++;
}
void main()
{
for(i=0;i<10;in(i));
clrscr();
printf("%d",i);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *p;
char s[]="dhankumaraa is a goood boy and he sincerely love his country";
clrscr();
p=s;
puts(p);
strcpy(p,s);
puts(p);
strncpy(p,s,sizeof(p));
puts(p);
strncpy(p,s,sizeof(p)+1);
puts(p);
strncpy(p,s,sizeof(s)+1);
puts(p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[12];
char s2[23];
clrscr();
printf("Enter a string :");
gets(s1);
printf("Enter a string");
fgets(s2,sizeof(s2),stdin);
printf("%d\n",strlen(s1));
printf("%d\n",strlen(s2));
printf("%d",(strlen(s1)-strlen(s2)));
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[12];
char s2[12];
clrscr();
printf("Enter a string");
gets(s1);
printf("Enter a string:");
fgets(s2,sizeof(s2),stdin);
printf("%d\n",strlen(s1));
printf("%d\n",strlen(s2));
printf("%d",strlen(s1)-strlen(s2));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
printf("Enter two numbes:");
scanf("%d %d",&i,&j);
j=i^j;
i^=j;
j^=i;
clrscr();
printf("%d %d",i,j);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("%d %d",sizeof a,sizeof (int ));
getch();
}
/*The build in datatype requires the paranthesis */
/*Where as the variable doesn't neeed the paranthesis */
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
void main()
{
; char *p=0;
p=(char *)malloc(4);
strcpy(p,"kumar");
clrscr();
printf("%s",p);
getch();
}
#include<stdio.h>
#include<conio.h>
struct kumar
{
int a[2];
}o;
void f(struct kumar v)
{
v.a[0]=1;
v.a[1]=1;
}
void main()
{
clrscr();
printf("%d %d\n",o.a[0],o.a[1]);
o.a[0]=2;
o.a[1]=2;
printf("%d %d",o.a[0],o.a[1]);
getch();
}
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<io.h>
#define fileno(fp) ((fp)->fd)
void main()
{
char b[12];
write(fileno(stdout),"Enter a string :",16);
gets(b);
write(fileno(stdout),b,strlen(b));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
(printf)("%d",i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Time :%s\n",__TIME__);
printf("File:%s\n",__FILE__);
printf("Line:%s\n",__LINE__);
printf("Date:%s\n",__DATE__);
#ifdef __STDC__
printf("STDC:%s\n",__STDC__);
#endif
getch();
}
#include<stdio.h>
#include<conio.h>
#include<assert.h>
void f(int i)
{
assert(i<4);
}
void main()
{
clrscr();
int i;
for(i=0;i<10;i++)
{
f(i);
printf("%d\n",i);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char *p;
char *q;
clrscr();
printf("%Fp %Np",p,q);
getch();
}
/*pointer size modifier are 'F' and 'N', hence the address for the two
pointers differs */
#include<stdio.h>
#include<conio.h>
void main()
{
enum ra
{
j,k};
enum ra o;
clrscr();
printf("%d %d\n",j,k);
o=j;
o+=6;
printf("%d %d\n",o,j);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
struct
{
char n[12];
struct
{
char v[12];
}o;
}p={"kumar","kumaresh"};
clrscr();
printf("%s %s",p.n,p.o.v);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
struct kumar
{
char c[12];
char *p;
int i;
float f;
}o={"raajesh"};
clrscr();
printf("%s %s %d %f",o.c,o.p,o.i,o.f);
getch();
}
/*During the initialization of the structure variable if the first fields
value is given and the remainig members values are not given ,then the other
meebres are initialized to zero automatically */
#include<stdio.h>
#include<conio.h>
void main()
{
struct
{
struct
{
int i;
char c;
}o={12,'A'};
}w;
clrscr();
printf("%d",w.o.i);
getch();
}
/*the above structure is attempting to initialize a struct member
which inturn a structure ,that is not possible in C
hence the error*/
#include<stdio.h>
#include<conio.h>
void main()
{
struct a
{
char c[7];
char *p;
};
struct b
{
char *o;
struct a u;
};
struct b w={"kumar","ravi","vijay"};
clrscr();
printf("%s %s\n",w.o,w.u.p);
printf("%s %s\n",++w.o,++w.u.p);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
union
{
int i;
char c[2];
}o;
clrscr();
o.c[0]=3;
o.c[1]=2;
printf("%d %d %d",o.c[0],o.c[1],o.i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i=getch();
if(!i)
i=getch()+128;
printf("%d",i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,*p;
p=&i;
*p=0;
++*p++;
clrscr();
printf("%d",i);
getch();
}
/*the program contains a critical statement ++*p++ thi increments the *p
only once that is in the preincrement operation and left the value being
incremented postwards */
/*if you include a paranthesis before the post increment operator the
post incrementation takes place */
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[3][3][3]={ {1,2,3,4,5,6,7,8,9},
{2,4,6,8,10,12,14,16,18},
{3,6,9,12,15,18,21,24,27}
};
static int *ptr[]={ a[0][0],a[0][1],a[0][2],
a[1][0],a[1][1],a[1][2],
a[2][0],a[2][1],a[2][2]
};
int *ptr1[]={a[0],a[1],a[2]};
int **ptr2=ptr,i;
clrscr();
printf("\n");
for(i=0;i<=8;i++)
{
printf("%d\n",**ptr2);
ptr2++;
//printf("%d\n",*(ptr[i]));
}
printf("\n");
for(i=0;i<=2;i++)
printf("%d\n",*(ptr1[i]));
printf("\n");
for(i=0;i<=8;i++)
printf("%d\n",*ptr[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[]={97,98,99,100,101,102,103,104};
int *p=a+1;
printf("%d %d %d %d %d ",*(++p),*(p--),*p,*(p++),*(++p));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3][2]={1,2,3,4,5,6,3,4,1,2,5,6,5,6,3,4,1,2};
clrscr();
printf("%d %d %d",*(*(a[0]+2)+1),*(*(*(a+2)+1)+1),*(a[1][2]+1));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[]={0,1,2,3,4};
static int *p[]={a,a+2,a+1,a+4,a+3};
int **p1;
p1=p;
clrscr();
++p1;
printf("%d %d %d",**p1,p1-p,*p1-a);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[1][1][2]={{1,2}};
int *pt=a[0];
clrscr();
printf("%u %u %u",a[0],*pt,**a[0]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[1][1][2]={1,2};
int *p;
clrscr();
p=a[0][0];
printf("%d %d ",p,*p);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char a[2][2][25]={ { "jack and jill", "Went up the
hill"}, { "jack fell down","and broke his
crown" }};
clrscr();
printf("%s %s %s %s",&a[0][0][9],&a[0][1][12],&a[1][0][10],&a[1][1][14]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s[]="C a of";
char t[]="is philosophy life";
char u[40];
char *ss=s,*tt=t,*uu=u;
clrscr();
while(*ss||*tt)
{
while(*ss)
{
if((*uu++=*ss++)==' ')
break;
}
while(*tt)
{
if((*uu++=*tt++)==' ')
break;
}
*uu='\0';
puts(u);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d",sizeof '2');
getch();
}
/*THE same program will produce different result in the turboc2 compiler
that is in pure C compiler the value will be 2 because the character
in C are stored as integers hence two butes are required */
#include<stdio.h>
#include<conio.h>
#define min(i,j) ((i)<(j)?(i):(j))
int minf(int i,int j)
{
return (i<j?i:j);
}
int f()
{
printf("f() is called\n");
return 12;
}
int g()
{
printf("g() is called \n");
return 21;
}
void main()
{
clrscr();
printf("The macro\n");
printf("%d\n",min(f(),g()));
printf("The function \n");
printf("%d\n",minf(f(),g()));
getch();
}
#include<stdio.h>
#include<conio.h>
int i;
int f()
{
printf("f() is called \n");
i+=4;
return i;
}
int g()
{
printf("g() is called \n");
i+=2;
return i;
}
void main()
{
clrscr();
printf("%d %d",f(),g());
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
f(12,122);
getch();
}
f()
{
printf("kumar");
}
/*A function , by default ,sends a integer type parameters and returns
an int type value */
#include<stdio.h>
#include<conio.h>
/*int i=12;*/
void main()
{
static int h=i;
clrscr();
printf("%d ",h);
getch();
}
/*static variable can only be initialized by a constant expression or a
constant value and static variable cannot be initialized by the local
variable or by using a global variable */
#include<stdio.h>
#include<conio.h>
void main()
{
static int i=printf("kumar");
clrscr();
printf("%d",i);
getch();
}
/*you cannot initialize the static variable by using a run time function
hence the error */
#include<stdio.h>
void main()
{
int i;
clrscr();
printf("Enter an integer :");
scanf("%d",&i);
switch(i)
{
case 1:
printf("kumar");
continue;
}
getch();
}
/*'continue' statement cannot be placed inside the switch statement */
/*In the similar way 'break' statement cannot be placed inside the for loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
static int i;
i=printf("kumar\n");
printf("%d",i);
getch();
}
/*here the program works because first the static variable does not have
any initializer hence it is initialized to zero but when the printf() comes
in to picture ,it is a run time function it returns the no of characters
outputed hence the static variable is given the value of 4 */
#include<stdio.h>
#include<conio.h>
char * f();
void main()
{
clrscr();
printf("%s",f());
getch();
}
char* f()
{
char s[]="kumar";
return s;
}
/*Here the output is a magic because the variable s[] is an automatic
variable ,that is the variable is created and destroyed inside the function
but you are trying to return the address the destroyed variable hence the
garbage value printed */
/*The solution to this problem is to declare the variable as static storage
class */
#include<stdio.h>
#include<conio.h>
extern void f()
{
printf("kumar");
}
void main()
{
clrscr();
f();
getch();
}
/*you can also use the keywords extern and static in the function definition
normally you cannot define a extern variable (ie.) a variable name preceded
by the keyword extern cannot define a new value (ie..) extern int n=12;
this statement tries to define a variable which is defined elsewhere*/
#include<stdio.h>
void main()
{
char s[]="kumar";
static char *p=s;
clrscr();
printf("%s",s);
getch();
}
/*The pointer p is present in the initialized data area .This is a load time
variable.So the pointer should be initialized before program execution
When compiling the program tries to initialize the pointer to the address
of the first element of the array which is not created yet on the stack .
This an incorrect usage of the storage class and thus the error isgenerated */
#include<stdio.h>
#include<conio.h>
void cdecl c_conv();
void pascal p_conv();
void main()
{
int a=1,b=2,c=3;
clrscr();
c_conv(a,b,c);
p_conv(a,b,c);
getch();
}
void cdecl c_conv(int i,int j)
{
printf("i=%d j=%d\n",i,j);
}
void pascal p_conv(int i,int j)
{
printf("i= %d j=%d",i,j);
}
/*Because the C calling convention pushes the arguments in the reverse
order but the Pascal calling convention pushes the arguments in the
order they comes */
#include<stdio.h>
void main()
{
clrscr();
printf("%d",sizeof("kumar"));
getch();
}
/*the output includes the '\0' character */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
a=4;
b=sizeof(++a);
printf("%d %d",a,b);
getch();
}
/*The reason behind this output is that if the sizeof operator is applied
to an expression the compiler does not compile it for executable code .Hence
in the case of sizeof operator the operation in expression do not have any
side effects which was logically expected */
#include<stdio.H>
#include<conio.h>
void main()
{
typedef static int a;
}
/*The typedef statement cannot have storage class */
#include<stdio.h>
#include<conio.h>
void main()
{
static int c=sizeof('4');
clrscr();
printf("%d",c);
getch();
}
/*This program works because the sizeof operator is a compile time
operator */
#include<stdio.H>
#include<conio.h>
void main()
{
extern int i;
clrscr();
printf("%d",i);
}
int i=4;
->
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=0,j=0;i<2,j<5;i++,j++)
printf("%d %d\n",i,j);
getch();
}
/*In the For loop if condition part is separated by comma operator ,then the
last separated condition becomes the condition for the For loop .Because
the comma operator associates from left to right */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i=1,j=2,k=3;
printf("Enter integer:");
scanf("%d,%d,*",&i,&j,&k);
printf("%d %d %d",i,j,k);
getch();
}
/*Here the * in the scanf function is the assignment operator */
#include<stdio.h>
#include<conio.H>
void main()
{
int i=-1;
clrscr();
-i;
printf("%d",i);
getch();
}
#include<stdio.H>
#include<conio.h>
void main()
{
int a=10,b=8,c;
clrscr();
--a;
- -b;
c=a-b;
printf("%d %d %d",a,b,c);
getch();
}
#include<stdio.H>
#include<conio.H>
void main()
{
int i,n,k;
int p[5]={1,2,3,4};
int q[5]={1,2,3,4};
clrscr();
i=1;
n=5;
p[i++] *=n;
printf("%d \n",i);
q[i++]=q[i++] *n;
printf("%d\n",i);
for(k=0;k<5;k++)
printf("%d\n",p[k]);
printf("\n");
for(k=0;k<5;k++)
printf("%d\n",q[k]);
getch();
}
/*In the above program in first expression 'i++' is executed once whereas
in the second expression it is evaluated twice */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,j=1;
int *a[]={&i,&j};
int s=sizeof(a)/sizeof(const int *);
int k;
for(k=0;k<s;k++)
printf("%d",*a[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
#define kumar(i) printf("i" #i "=%d\n",i##i)
void main()
{
int i1=2;
clrscr();
kumar(1);
}
#include<stdio.h>
#include<conio.H>
void f(void)
{
printf("kumar\n");
}
void main()
{
void (*p) (void);
p=f;
clrscr();
(*p)();
p();
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,2,3};
static int *p[]={a,a+1,a+2};
clrscr();
printf("%d %d %d\n",*p[0],*p[1],*p[2]);
getch();
}
#include<stdio.h>
struct kumar
{
int a :10;
}o;
void main()
{
clrscr();
printf("%d",&o.a);
getch();
}
/*The data type bitfield ia an integer subfield. It is always declared as a
member of a structure. Since bitfield is less than a byte, it has no address
therfore you may not use the address operator to the bitfield */
#include "ra.h"
#include<stdio.h>
void main()
{
printf("kumar");
getch();
}
/*You cannot include the header file itself .Hence the error
Here the content of the "ra.h" is #include "ra.h" */
#include<stdio.h>
#include<conio.h>
#define swap(D,x,y) {D k=x;x=y;y=k;}
void main()
{
int a=4,k=2;
clrscr();
swap(int,a,k);
printf("%d %d",a,k);
getch();
}
/*The output is just 4 2 .that means the variables has not been changed
their values .The mistake here is the the clash between the variable
defined in the main() and the macro variable */
#include<stdio.h>
#include<conio.H>
void main()
{
printf("kumar");
}
/*Even though the C language is a free format language but the
#include directive s cannot be written on one line*/
#include<stdio.h>
#include<math.h>
main()
{
clrscr();
printf("%lf",sqrt(4));
getch();
}
/*The output is a miracle because you have included the math.h header file
on your source code .But the mistake here is that you have included
the header files on one line */
#include<stdio.h>
#define kumar(i,j) (i##j)
#include<conio.H>
void main()
{
clrscr();
printf("%d",kumar(1,2));
getch();
}
/*The above program use the token pasting symbol */
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen("kumar","r+");
clrscr();
printf("%d\n",fp->level);
printf("%d\n",fp->flags);
printf("%d\n",fp->fd);
printf("%d\n",fp->hold);
printf("%d\n",fp->bsize);
printf("%d\n",fp->buffer);
printf("%d\n",fp->curp);
printf("%d\n",fp->istemp);
printf("%d\n",fp->token);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char m[]="Life is Great";
FILE *fp;
fp=fopen("kumar","w");
clrscr();
printf("After opening the file\n");
printf("Buffer = %d\n",fp->buffer);
printf("Curp= %d\n",fp->curp);
fprintf(fp,m);
printf("\n");
printf("After wriring the message\n");
printf("Buffer = %d\n",fp->buffer);
printf("Curp= %d\n",fp->curp);
fflush(fp);
printf("\n");
printf("After executing the fflush function\n");
printf("Buffer =%d\n",fp->buffer);
printf("Curp=%d\n",fp->curp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d %#X %#o",EOF,EOF,EOF);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%u",main);
main++;
printf("%u",main);
getch();
}
/*You cannnot increment the function name as in the case of the array name
Even though the function name is the starting address of the function main
in the memory .Hence the name of the function is also a constant pointer */
#include<stdio.h>
#include<conio.h>
#define START 100
void main()
{
clrscr();
goto START;
printf("Kumar");
START:
printf("Kumaresh");
getch();
}
/*The use of symbolic constant as labels is not permitted in the Goto
statement */
#include<stdio.h>
#include<conio.h>
main()
{
int i=10;
clrscr();
printf("%d\n",i);
{
#include<stdio.h>
#include<conio.h>
int j=11;
printf("%d\n",j);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void kumar(int i)
{
printf("%d",i);
}
void main()
{
int i=3;
clrscr();
kumar(++i*++i*++i/++i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
int j=i++ -i++;
clrscr();
printf("%d %d",j,i);
printf("%d",i++ - i++);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d",sizeof (void));
getch();
}
#include<stdio.h>
#include<conio.h>
struct kumar
{
void c;
}o;
void main()
{
clrscr();
printf("%d",sizeof o);
getch();
}
#include<stdio.h>
#include<conio.h>
union r
{
void m;
}o;
void main()
{
clrscr();
printf("%d",sizeof o);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
enum
{
RED=32768,
BLUE
}o;
clrscr();
o=RED;
printf("%d\n",o);
printf("%d\n",sizeof o);
getch();
}
/*The Enumerated datatype Can be an unsigned char ,signed char and int type
Hence their range is inbetweeen -32768 to +32767 */
#include<stdio.h>
void main()
{
void a[2];
clrscr();
printf("%d",sizeof a);
getch();
}
#include<stdio.H>
#include<conio.h>
void main()
{
int *p,*q;
int a,b;
clrscr();
/* p=(int *)1000;
q=(int *)2000; */
p=&a;
q=&b;
printf("%u\n",p);
printf("%u\n",q);
printf("%u",p-q);
getch();
}
#include<stdio.h>
void main()
{
int *p;
double *q;
int a;
double d;
clrscr();
p=&a,q=&d;
printf("%u %u\n",p,q);
/* p=(int *)1000;
q=(double *)2000;*/
printf("%d",q-p);
getch();
}
/*In pointer subtraction whatever the type of the two pointers is immater
The scale factor for the pointer subtraction is the size of the first pointers
pointing object*/
#include<stdio.h>
#include<conio.h>
struct kumar
{
float p;
}*o;
void main()
{
int *q;
clrscr();
o=(struct kumar *)2000;
q=(int *)1000;
clrscr();
printf("%d",o-q);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void dis(int n,...)
{
char c;
int j;
va_list p;
va_start(p,n);
for(j=0;j<n;j++)
printf("%c\n",va_arg(p,int));
va_end(p);
}
void main()
{
clrscr();
dis(3,65,66,67);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void dis(int n,...)
{
char c;
int j;
va_list p;
va_start(p,n);
for(j=0;j<n;j++)
printf("%c\n",va_arg(p,int));
va_end(p);
}
void main()
{
clrscr();
dis(3,65,66,67);
getch();
}
#include<stdio.h>
void main()
{
int (*p[2][3]);
clrscr();
printf("%d",sizeof p );
getch();
}
#include<stdio.h>
#include<conio.h>
#define p(format,var) printf(#var"=""%"#format"\n",var)
void main()
{
int i=3;
float a=3.14;
clrscr();
p(d,i);
p(f,a);
getch();
}
#include<stdio.h>
#define kumar
void main()
{
clrscr();
#ifdef kumar
printf("kumar");
#else
printf("vijay");
#endif
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
window(10,10,40,20);
cprintf("ilove my country rasjkakaka akana k");
cprintf("all indians are ");
getch();
}
/*See carefully the cprintf() function ,you can understand the difference
botween the printf() function .Eventhough we have not included any
'\n' statement in our cprintf() function but the strings given to the
function are printed line by line. This is because cprintf() sees to it
that the output of our program goes only to this particular area on
the screen */
#include<stdio.h>
#include<string.h>
struct r
{
char *p;
int a;
};
void main()
{
FILE *fp;
struct r o[10];
struct r b;
int n;
strcpy(o[9].p,"dhankumar");
o[9].a=20;
fp=fopen("kumar","wb");
fwrite(o,sizeof(struct r),10,fp);
fclose(fp);
fp=fopen("kumar","rb");
clrscr();
printf("Enter the record number :\n");
scanf("%d",&n);
fseek(fp,(long)(n*sizeof(struct r)),0);
fread(&b,sizeof(struct r),1,fp);
printf("\n%s %d",b.p,b.a);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
register long double a=3.45E9;
clrscr();
printf("%u\n",&a);
printf("%Lf",a);
getch();
}
/* Note that the register storage reports an error when they are operated
with the '&' operator
The interesting thing in this problem is that the sizeof any CPU register \
is between 0 to 32 .Eventhough the size of the float is 4 bytes and the
sizeof long double is 10 bytes
*/
#include<stdio.h>
#include<conio.h>
void main()
{
extern int i;
clrscr();
printf("%d\n",i);
f();
getch();
}
int i=23;
f()
{
printf("%d\n",i);
}
/*The key line in this program is that the "extern int i;" theis tells the
copiler that the definition of the variable may be some where in the rest of
the program.Hence the compiler does not show any error.If you want to test
whethere if you remove this line you can surely get an error message*/
#include<stdio.h>
#include<conio.h>
main()
{
char *x;
clrscr();
printf("%u\n",x);
x="kumar";
printf("%u\n",x);
getch();
}
/*The pointer is made to point the memory location allocated for the constant
string "kumar" */
#include<stdio.h>
#include<alloc.h>
void main()
{
char p[]="hello world";
char *p1=malloc(5);
p1=p;
clrscr();
printf("%s\n",p1);
printf("%s",p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int i;
int *p=malloc(5*sizeof(int));
// realloc(p,5*sizeof(int));
for(i=0;i<10;i++)
p[i]=0;
clrscr();
for(i=0;i<10;i++)
printf("%d\n",i);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int i;
int *p=malloc(5*sizeof(int));
// realloc(p,5*sizeof(int));
for(i=0;i<10;i++)
p[i]=0;
clrscr();
for(i=0;i<10;i++)
printf("%d\n",i);
getch();
}
#include<stdio.h>
#include<conio.h>
void out(int x)
{
if(x!=0)
{
out(x/16);
putchar("0123456789ABCDEF"[x%16]);
}
else
putchar('\n');
}
void main()
{
clrscr();
out(1234);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
long int l=23;
int *p;
p=&l;
clrscr();
printf("%d",*p);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a=255;
char *p=&a;
clrscr();
printf("%d",*p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char b1[100]="Hello";
char b2[100]="World";
char *p1,*p2;
p1=b1+2;
p2=b2+3;
strcpy(p1,b2);
strcpy(p2,b1);
printf("%s %s",b1,b2);
getch();
}
#include<stdio.h>
void f(int );
void main()
{
f(x++);
}
int x=5;
void f(int p)
{
printf("%d",--p);
}
/*The error in this program is that the variable is not known at the compilation
time */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
a=b=c=-1;
d=++a||++b&&++c;
clrscr();
printf("%d %d %d \n",a,b,c);
printf("%d",d);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=b=c=-1;
clrscr();
printf("%d\n",++a&&++b||++c);
printf("%d %d %d",a,b,c);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *p;
clrscr();
p=(char *)memchr("This is a test",' ',8);
clrscr();
printf(p);
getch();
}
/*memchr searches the first n bytes of the block *p for character c.*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
int i=memcmp("kumaresh","kumaresh",0);
if(i<0)
printf("First is less than second");
else if(i==0)
printf("Equal");
else
printf("first is greater than second");
getch();
}
#include<stdio.h>
#include<alloc.h>
void main()
{
char *p;
p=malloc(5);
clrscr();
printf("%d",p);
free(p);
printf("\n%d",p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *p;
p=(char *)malloc(5);
clrscr();
strcpy(p,"kumar");
printf("%d\n",p);
p=(char *)realloc(p,5);
printf("%d\n%s",p,p);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("%d",1&&n=4);
getch();
}
#include<stdio.h>
#include<stdarg.h>
void kumar(char *p,...);
void main()
{
clrscr();
kumar("kumar",11,2,3,4);
getch();
}
void kumar(char *q,...)
{
va_list p;
va_start(p,q);
printf("%s\n",va_arg(p,char));
printf("%d\n",va_arg(p,int));
}
#include<stdio.h>
#include<conio.h>
void kumar(char *m,int n,...)
{
va_list p;
va_start(p,m);
printf("%d\n",va_arg(p,int));
printf("%d\n",va_arg(p,int));
}
void main()
{
clrscr();
kumar("kumar",1,2,123,45);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void kumar(char *s,...)
{
va_list p;
va_start(p,s);
printf("%d %d %d %d",va_arg(p,int),va_arg(p,int),va_arg(p,int),va_arg(p,int));
printf("%c",va_arg(p,char));
}
void main()
{
char a='a';
clrscr();
kumar("kumar",1,2,135,23,'a');
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void kumar(int n,...)
{
char c;int j;
va_list p;
va_start(p,n);
for(j=0;j<n;j++)
{
c=va_arg(p,char);
printf("%c\n",c);
}
}
void main()
{
clrscr();
kumar(4,'A','B','C','D');
getch();
}
/*The result is very different because the given arguments are charaters A,B,
C,D But the printed result is only A ,space ,B,space .This is because
during getting the argument from the argument list in the va_args(p,char) we
use the char so the compiler takes the 1 bytes of each of the argument and
prints the result
Normally in the memory the integer is stored in the order of first the
high order byte and the low order byte next*/
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void kumar(char *q,...)
{
va_list p;
va_start(p,q);
printf("%s\n",va_arg(p,char *));
printf("%s\n",va_arg(p,char *));
}
void main()
{
char *p="kumar";
char a[]="vall";
clrscr();
kumar("kumar",p,a);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void kumar(int n,...)
{
va_list p;
va_start(p,n);
printf("%f",va_arg(p,double));
}
void main()
{
clrscr();
kumar(1,12.34);
getch();
}
/*If you change the datatype being picked from the argument list as float
then the program wont print the required answer */
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void kumar(char *p,...)
{
va_list q;
va_start(q,p);
f(p,q);
}
f(char *p,va_list e)
{
printf("%d",va_arg(e,int));
}
void main()
{
clrscr();
kumar("kumar",4);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
void f1()
{
printf("kumar\n");
}
void f2()
{
printf("vijay");
}
void kumar(int n,...)
{
typedef void (*q)();
q a,b;
va_list p;
va_start(p,n);
a=va_arg(p,q);
a();
b=va_arg(p,q);
b();
}
void main()
{
void (*p1)();
void (*p2)();
p1=f1;
p2=f2;
clrscr();
kumar(2,p1,p2);
getch();
}
/*The important thing to note here is that when you are retirving the
argument list the funtion pointer cannot be retrived as void (*)() */
#include<stdio.h>
void main()
{
float (*p)[4];
clrscr();
printf("%d",sizeof *p);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][4][3];
clrscr();
printf("%d",sizeof **a);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2];
clrscr();
printf("%d\n",sizeof *(a));
printf("%d",sizeof *(a+1));
getch();
}
#include<stdio.h>
#include<conio.H>
void main()
{
char c=128;
int i;
clrscr();
i=c;
printf("%d\n",i);/*Here sign extension takes place*/
printf("%d",c);
getch();
}
#include<stdio.H>
#include<conio.h>
void main()
{
float f=23.45;
double d;
long double ld;
clrscr();
printf("%lf\n",d=f);
printf("%Lf",ld=f);
getch();
}
/*The program here just output the result very easily.But the main point
here is to note that if you change the format specifier of the seconmd
printf () statement to %lf that is the format specifier of the float
the output will be -0.000*/
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
1?x=2:y=2;
printf("%d %d",x,y);
getch();
}
/*The point here is to note is that the conditional operator is having
precedence more than the assignment operator and comma operator .And the
way the conditional operator executed is that it puts brackets for its token
that is (1?x=2:y)=2 so the compiler could not know where to store the value 2
hence the error lvalue required is obtained */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=2;
clrscr();
0?i++:2?--i:i++;
printf("%d",i);
getch();
}
/*The conditional operator is executed form right to left .The conditional
expression is written as (0?i++:(2?--i:i++)) */
#include<stdio.h>
#include<conio.h>
void main()
{
int x=1,y=3,t;
int r;
float y1=2.3;
clrscr();
r=(t=x,x=y,y=t);
printf("%d\n",r);
printf("%f",(x=1,y1+x));
getch();
}
#include<stdio.H>
#include<conio.h>
void main()
{
int *p,*q;
int a[]={1,2,3,4,5};
clrscr();
p=a;
q=a;
if(p<=q)
printf("p is less than q");
else
printf("Q is less than p");
getch();
}
/*The point here is to note is that we can apply relation operators as <.>
<=,>=to pointers pointing to the same object*/
/*The relation operator == and != can be applied to pointers of same type
,pointer of any other type and void * type ponter*/
#include<stdio.h>
#include<conio.h>
void main()
{
int *p;
char *q;
clrscr();
p=(int *)2000;
q=(char *)2000;
if(p<q)
printf("p is less than q");
else if (p>q)
printf("p is greater than q");
else if (p==q)
printf("P and q are equal");
else
printf("p and q are not equal");
getch();
}
/*You can also compare the pointers of different type using the relation
operators*/
#include<stdio.h>
#include<conio.h>
void main()
{
void *p;
clrscr();
printf("%d",sizeof p);
getch();
}
/*The sizeof the pointer to a void datatype is als two bytes*/
#include<stdio.h>
#include<conio.h>
void main()
{
void *p[3];
/* void (*p1)[3];*/
clrscr();
printf("%d\n",sizeof p);
printf("%d",sizeof p1);
getch();
}
/*You cannot an array void type but you can have an array of pointers
of any dimension of type void
And you cannot have an pointer to an array of type void */
#include<stdio.h>
#include<conio.h>
void main()
{
void *p;
clrscr();
printf("%d %d\n",p,NULL);
if(p==NULL)
printf("p and NULL pointers are equal");
else
printf("p and NULL pointers are not equal");
getch();
}
/*The point here to note is that the void *p that is a generic pointer
is not equal to the NULL pointer
And you can have an address assigned to the void pointer initially*/
#include<stdio.h>
#include<conio.h>
void main()
{
char (*c)[4];
char a[][4]={"kumar","ram","via"};
int i;
c=a;
clrscr();
for(i=0;i<3;i++)
printf("%s\n",c[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char (*c)[4];
char *a[4];
int i,n;
clrscr();
// c=a;
printf("Enter the no of string :\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the string:\n");
scanf("%s",&c[i]);
}
printf("Press any key to continue............\n");
getch();
clrscr();
printf("The string as follows ...............\n");
for(i=0;i<n;i++)
printf("%s\n",c[i]);
getch();
}
/*The above program allows you to get the strinigs at runtime using
pointer to an array of char*/
#include<stdio.h>
#include<conio.h>
void main()
{
int **p;
int i,j;
clrscr();
p=(int **)malloc(2*sizeof (int *));
for(i=0;i<2;i++)
p[i]=(int *)malloc(2*sizeof (int));
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
printf("Enter a number:\n");
scanf("%d",&p[i][j]);
}
clrscr();
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("%d\n",p[i][j]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char **p;
int i,j;
clrscr();
p=(char **)malloc(sizeof (char *));
for(i=0;i<3;i++)
{
p[i]=(char *)malloc(5);
printf("Enter the string:\n");
scanf("%s",p[i]);
}
clrscr();
for(i=0;i<3;i++)
printf("%s\n",p[i]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
void *p;
int *ip;
float *fp;
*ip=12;
clrscr();
p=ip;
ip=p;
printf("%u %u\n",p,ip);
printf("%d\n",*ip);
p=fp;
fp=p;
*fp=12.34;
printf("%u %u\n",p,fp);
printf("%f",*fp);
getch();
}
/*The above program illustrates the point is that any pointer of any type
can be converted in to void * type and back without loss of information*/
#include<stdio.h>
#include<conio.h>
void main()
{
struct r
{
int w:1;
}o;
clrscr();
printf("%d",&o.w);
}
/*You cannot take address for the bitfield */
#include<stdio.h>
#include<conio.h>
void main()
{
struct ra
{
unsigned i:2;
signed j:2;
}o;
clrscr();
printf("%d",sizeof o);
getch();
}
/*The output of the above program is simple but the need for this program
is that what are the datatypes that can be made as bitfields.The answer
for this question is the above program (ie..) only int can used .You cannot
also made char and unsigned char as bitfield*/
#include<stdio.h>
#include<conio.h>
void main()
{
union r
{
int i:1;
}o;
clrscr();
printf("%d",sizeof o);
getch();
}
/*The output of the above program is simple.But the point to remember
is that the union datatype also supports the bitfields*/
#include<stdio.h>
#include<conio.h>
void main()
{
int *p;
clrscr();
printf("Enter a address");
scanf("%d",p);
printf("%d",*p);
getch();
}
/*here in the program is that the adress what we are typing is stored
as the value in the pointer */
#include<stdio.h>
#include<conio.h>
void main()
{
volatile int *p;
clrscr();
printf("%d",p);
getch();
}
/*The above illustrates that the pointer can have modifier volatile as their
object*/
#include<stdio.h>
#include<conio.h>
void kumar(i)
{
printf("%d",i);
}
void main()
{
clrscr();
kumar(21);
getch();
}
/*The above program illustrates that the default type argument passed to
the function is of type int */
#include<stdio.h>
#include<conio.h>
void main()
{
int *p;
clrscr();
printf("kumar\n");
printf("%n\n",p);
printf("%d\n",*p);
getch();
}
/*The %n specifier in the printf() cause the no of characters that has been
outputed by this function call till the %n specifier is reached in the
printf,the %n specifier does not output any argument or do any operation*/
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,q;
clrscr();
scanf("%d%n",&q,p);
printf("%d",*p);
getch();
}
/*The above program illustrates the use of the %n specifier in the scanf()
function .The no of characters read from the input so far by this callto
scanf() is written in to the variable pointed to by the correspomding
argument,which must be of type int * */
#include<stdio.h>
#include<conio.h>
void main()
{
char *p;
static char q[]="kumar";
clrscr();
p=q;
clrscr();
printf("%s %s\n",p,q);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char p1[100];
char p2[100];
clrscr();
printf("Enter a string:\n");
gets(p1);
printf("Enter a strinig:\n");
fgets(p2,sizeof p2,stdin);
printf("%d %d",strlen(p1),strlen(p2));
getch();
}
/*The important thing to note is that the newline character is discarded
in the gets() but it is included in the second function*/
#include<stdio.h>
#include<conio.h>
void main()
{
char *p="car";
clrscr();
printf("%c\n",*(p+2));
printf("%c\n",(&p)[0][2]);
printf("%c\n",*p+2);
printf("%c\n",p[2]);
printf("%c",2[p]); /*But not [2]p*/
getch();
}
#include<stdio.h>
void main()
{
char *p=NULL;
clrscr();
printf("%s",p);
getch();
}
#include<stdio.h>
#include<string.h>
#include<alloc.h>
char *kumar(char *p)
{
char *t=(char *)malloc(strlen(p));
return (strcpy(t,p));
}
void main()
{
clrscr();
printf("%s",kumar("kumar"));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
struct r
{
static int i;
}o;
clrscr();
o.i=4;
printf("%d",o.i);
getch();
}
/*The above program illustrates that the members of the structure cannot be
static. Similarly the members of the union also cannot be static */
#include<stdio.h>
#include<conio.h>
void main()
{
float f=12.34;
clrscr();
printf("%d",f>>2);
getch();
}/*The above program shows that the bitwise operator cannot be applied to
the floating point datatype*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
i=i++*i++*i++;
clrscr();
printf("%d",i);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
typedef static int a;
a b;
clrcr();
printf("%d",b);
getch();
}
/*The above program shows that in the typedef statement you cannot create
a synonmous name for the datatype having storage class*/
#include<stdio.h>
#include<conio.h>
void f()
{
printf("Hai");
}
void main()
{
struct r
{
void (*p)();
}o;
clrscr();
o.p=f;
o.p();
getch();
}
/*The above program illustrates that the member of a structure can be
a fuction pointer */
#include<stdio.h>
#include<conio.h>
void main()
{
char c[]="%s is a string";
clrscr();
printf(c,c);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a=3,b;
int *p;
clrscr();
p=&a;
b=a/*p;
printf("%d",b);
getch();
}
/*The erro here is the Unexpected end of file in comment*/
#include<stdio.h>
#include<malloc.h>
#include<string.h>
char *f()
{
}
void main()
{
char* f();
clrscr();
printf("%c",*f()='s');
getch();
}
#include<stdio.h>
#include<conio.h>
int *p()
{
}
void main()
{
int *p();
clrscr();
printf("%d",*p()=12);
getch();
}
/*The output of the program is simple to understand. the return type of the
function is int * but we have not returned any int * .but C returns an
integer pointer .then we are trying to store the value 12 in that lvalue
returned by the C compiler .Hence the assignment of 12 in that location
takes place and printf() outputs that value*/
#include<stdio.h>
#include<conio.h>
#define MAX(i,j) (i)>(j)?(i):(j)
void main()
{
int i=10,j=5,k=0;
k=MAX(i++,++j);
clrscr();
printf("%d %d %d",i,j,k);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char a,b;
clrscr();
printf("Enter a character:\n");
scanf("%c",&a);
printf("Enter character :\n");
scanf("%c",&b);
printf("The characters are %c %c",a,b);
getch();
}
/*The output is miracle because for the first input you have typed 'a'
and you are unable to give input to the second printf statement .This
is because as you give input to the computer through the scanf ()
function those inluts are storedin the buffer hence the character 'a'
followed by the character '\n' is stored */
#include<stdio.h>
#include<conio.h>
void main()
{
struct s1
{
int i;
}q;
struct s2
{
int i;
}p;
q.i=5;
p=q;
printf("%d",p.i);
getch();
}
/*The point here to note that you cannot assign the variables of two
different structures eventhough their members are same*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a=2,b=3;
clrscr();
printf("%d",a+++b);/* a++ + b*/
getch();
}
#include<stdio.h>
#include<conio.h>
#define pr(a) printf("%d",a)
#define print(a,b,c) pr(a),pr(b),pr(c)
#define max(a,b) (a<b)?a:b
void main()
{
int x=1,y=2;
clrscr();
print(max(x++,y),x,y);
printf("\n");
print(max(x++,y),x,y);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,j;
clrscr();
j=(i++?i++:i++)*i++ * i++;
printf("%d",j);
getch();
}
/*The conditional operator is executed first and then the multiplication
operator is executed .and the important thing is that the value of
i before the multiplication is 3 and C uses the same value till the end of
the expression .And increments the value of i by 2 after the completion
of the expression */
#include<stdio.h>
#include<conio.h>
void f(int *p[2])
{
printf("%d\n",p[0][0]);
}
void f1(int (*p)[4])
{
printf("%d\n",p[0][0]);
}
void f2(int p[][4])
{
printf("%d\n",p[0][0]);
}
void main()
{
int a[2][4]={1,2,3,4};
clrscr();
f(a);
f1(a);
f2(a);
getch();
}
#include<stdio.h>
#include<conio.h>
int *f()
{
return (int *)1000;
}
void main()
{
clrscr();
printf("%d",*f()=4);
getch();
}
/*In the above program if you let the compiler to return an integer address
and then the null poniter assignment exist .You can also return the address
of an integer variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
struct r
{
char s[12];
int i;
float f;
};
struct r o={"kumar"};
clrscr();
printf("%d %f",o.i,o.f);
getch();
}
#include<stdio.h>
#include<conio.h>
#define PR(x) printf("x=%.8g\n",(double)x)
#define PR4(x1,x2,x3,x4) PR(x1),PR(x2),PR(x3),PR(x4)
void main()
{
double d;
float f;
long l;
int i;
clrscr();
i=l=f=d=100/3;PR4(i,l,f,d);
d=f=l=i=100/3;PR4(i,l,f,d);
d=f=l=i=(double)100/3;PR4(i,l,f,d);
i=l=f=d=(double)(100000/3);PR4(i,l,f,d);
d=f=l=i=100000/3;PR4(i,l,f,d);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
x=y=z=-1;
++x&&++y||++z;
clrscr();
printf("%d %d %d",x,y,z);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char a[]={"w",'r'};
char a[]={'q',"kumar"};
}
/*These two statements are invalid*/
#include<stdio.h>
#include<conio.h>
void main()
{
int k=36,*p,*q;
clrscr();
*p++=(*q)++;
printf("%d",k);
getch();
}
/*The statement (*p)++ = (*q)++ displays an error message Lvalue required
because the compiler evaluates the right hand side first then the it
assign the computed value in to an Lvalue (ie..)an address but the output
of the left hand side is an rValue hence the error */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2]={1,1,1,1};
int*p=a,i;
clrscr();
for(i=0;i<4;i++)
printf("%d\n",p[i]);
getch();
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int a[][4]={{1,2,3},{1,3,5},{2,4,6},{4,8}};
int n[][4]={1,2,3,1,3,5,2,4,6,4,8};
clrscr();
printf("%d %d\n",a[2][2],n[2][2]);
printf("%d %d\n",a[0][3],n[0][3]);
printf("%d %d\n",a[1][3],n[1][3]);
printf("%d %d\n",a[2][3],n[2][3]);
printf("%d\n",a[3][3]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int (*p)[3];
int a=4,b=14,c=24;
clrscr();
*p[0]=a;
*p[1]=b;
*p[2]=c;
printf("%d\n",**p);
p++;
printf("%d\n",**p);
getch();
}
#include<stdio.h>
#include<conio.h>
struct r
{
struct r* (*fp)();
};
struct r* f()
{
printf("kumar\n");
return f;
}
void main()
{
struct r *(*p)();
clrscr();
p=f();
p();
getch();
}
#include<stdio.h>
#include<conio.h>
int (*f())()
{
printf("kumar\n");
return f;
}
void main()
{
int (*fp)();
clrscr();
fp=f();
fp();
getch();
}
#include<stdio.h>
#include<conio.h>
typedef int (*p)();/*Generic function pointer */
typedef p (*fp)();/*pointer to the generic pointer*/
fp f()
{
printf("kumar\n");
return f;
}
void main()
{
fp q;
clrscr();
q=f();
q();
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,2,3};
int (*p)[3]=a;;
clrscr();
printf("%d %d %d" ,p[0][0],p[0][1],p[0][2]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int (*p)[3];
int a=4,b=14,c=24;
clrscr();
*p[0]=a;
*p[1]=b;
*p[2]=c;
printf("%d %d %d",**p,**(p+1),**(p+2));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,2,3};
int (*p)[3]=a;
clrscr();
printf("%d %d %d\n",p[0][0],p[0][1],p[0][2]);
printf("%d %d %d\n",**p,*(*p+1),*(*p+2));
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int (*p)[1];
int a=4,b=14,c=24;
*p[0]=a;
*p[1]=b;
*p[2]=c;
clrscr();
printf("%d %d %d\n",&a,&b,&c);
printf("%d %d %d ",p[0],p[1],p[2]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int (*p)[2];
int a[]={1,2};
p=&a;
clrscr();
printf("%d %d",p[0][1],p[0][0]);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
const int a[2];
clrscr();
printf("%d %d ",a[0],a[1]);
getch();
}
/*All the constant variable of the primitive type should be initialized
at the time of declaration itself but not the aggregate type */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d",f());
getch();
}
f()
{
printf("r");
}
#include<stdio.h>
#include<conio.H>
void main()
{
char c=255;
int i=c;
clrscr();
printf("%#x",i);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define ROW 2
#define COL 2
void main()
{
int *p,i,j;
clrscr();
p=(int *)malloc(ROW*COL*sizeof (int));
for(i=0;i<ROW;i++)
for(j=0;j<COL;j++)
{
p[i*COL+j]=12;
printf("%d\n",p[i*COL+j]);
}
getch();
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int **p;
int i,j;
clrscr();
p=(int **)malloc(2*sizeof (int *));
p[0]=(int *)malloc(2*2*sizeof (int ));
for(i=0;i<2;i++)
p[i]=p[0]+i*2;
printf("%d %d",p[0],p[1]);
getch();
}
#include<stdio.h>
void day(int,int,int);
char days[7]
[10]={"saturday","sunday","monday","tuesday","wednessday",
"thursday","friday"};
int mon[12]={31,28,31,30,31,30,31,31,30,31,30,31};
void main()
{
char month[12][15]={"January","Febrauary","March","April","May","June",
"July","August","September","October","November","December"};
static int d,m,tdays,i,t1,t2,y,count=0,prnt=0;
clrscr();
printf("\t\t THE DAY OF GIVEN DATE, MONTH & YEAR\n");
printf("\t\t\tCALENDER FOR THE GIVEN YEAR\n");
printf("\n\nEnter the date, month & year:\n");
scanf("%d%d%d",&d,&m,&y);
day(d,m,y);
printf("\n\n\nPress any key for printing the %d calender.\n",y);
getch();
for(m=1;m<=12;m++)
{
if(y%4==0) mon[1]=29;
for(i=0;i<m-1;i++) t1+=mon[i];
tdays=(365*(y-1)+t1+(y/4)+1);
t2=tdays%7;
clrscr();
printf("\n\n\n %s %d\n",month[m-1],y);
printf("\n sun mon tue wed thu fri sat\n\n");
if (t2==0) t2=7;
for(i=1;i<t2;i++)
{
printf(" ");
count++;
}
while(prnt<mon[m-1])
{
if (count==7)
{
printf("\n\n");
count=0;
}
printf("%8d",++prnt);
count++;
}
getch();
t1=0;
count=0;
prnt=0;
}
}
void day(int d,int m,int y)
{
static int t1,tdays,i,t2;
if(y%4==0) mon[1]=29;
for(i=0;i<m-1;i++) t1+=mon[i];
tdays=(365*(y-1)+t1+(y/4)+d);
t2=tdays%7;
printf("\nThe given day is... %s",days[t2]);
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void print(FILE *fp)
{
char s[80];
while(fgets(s,80,fp))
printf("%s",s);
}
void main(int argc,char *argv[])
{
char s[80];
FILE *fp;
clrscr();
if(argc<2)
print(stdin);
else
{
int i;
for(i=1;i<argc;i++)
{
if(!(fp=fopen(argv[i],"rt")))
perror(argv[i]);
else
print(fp);
fclose(fp);
}
}
getch();
}
#include<stdio.h>
#include<conio.H>
void main()
{
unsigned int i=-10;int j=-10;
clrscr();
printf("%#x %#x",(int )i,j);
getch();
}
I have found that often the main reason beginners have a problem with pointers is that they have a weak or minimal
feeling for variables, (as they are used in C). Thus we start with a discussion of C variables in general.
A variable in a program is something with a name, the value of which can vary. The way the compiler and linker
handles this is that it assigns a specific block of memory within the computer to hold the value of that variable. The
size of that block depends on the range over which the variable is allowed to vary. For example, on PC's the size of
an integer variable is 2 bytes, and that of a long integer is 4 bytes. In C the size of a variable type such as an integer
need not be the same on all types of machines.
When we declare a variable we inform the compiler of two things, the name of the variable and the type of the
variable. For example, we declare a variable of type integer with the name k by writing:
int k;
On seeing the "int" part of this statement the compiler sets aside 2 bytes of memory (on a PC) to hold the value of
the integer. It also sets up a symbol table. In that table it adds the symbol k and the relative address in memory where
those 2 bytes were set aside.
In a sense there are two "values" associated with the object k. One is the value of the integer stored there (2 in the
above example) and the other the "value" of the memory location, i.e., the address of k. Some texts refer to these
two values with the nomenclature rvalue (right value, pronounced "are value") and lvalue (left value, pronounced "el
value") respectively.
In some languages, the lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address
where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the
assignment statement, the 2 above. Rvalues cannot be used on the left side of the assignment statement. Thus: 2 = k;
is illegal.
Actually, the above definition of "lvalue" is somewhat modified for C. According to K&R II (page 197): [1]
However, at this point, the definition originally cited above is sufficient. As we become more familiar with pointers
we will go into more detail on this.
Okay, now consider:
int j, k;
k = 2;
j = 7; <-- line 1
k = j; <-- line 2
In the above, the compiler interprets the j in line 1 as the address of the variable j (its lvalue) and creates code to
copy the value 7 to that address. In line 2, however, the j is interpreted as its rvalue (since it is on the right hand side
of the assignment operator '='). That is, here the j refers to the value stored at the memory location set aside for j, in
this case 7. So, the 7 is copied to the address designated by the lvalue of k.
In all of these examples, we are using 2 byte integers so all copying of rvalues from one storage location to the other
is done by copying 2 bytes. Had we been using long integers, we would be copying 4 bytes.
Now, let's say that we have a reason for wanting a variable designed to hold an lvalue (an address). The size required
to hold such a value depends on the system. On older desk top computers with 64K of memory total, the address of
any point in memory can be contained in 2 bytes. Computers with more memory would require more bytes to hold
an address. Some computers, such as the IBM PC might require special handling to hold a segment and offset under
certain circumstances. The actual size required is not too important so long as we have a way of informing the
compiler that what we want to store is an address.
Such a variable is called a pointer variable (for reasons which hopefully will become clearer a little later). In C when
we define a pointer variable we do so by preceding its name with an asterisk. In C we also give our pointer a type
which, in this case, refers to the type of data stored at the address we will be storing in our pointer. For example,
consider the variable declaration:
int *ptr;
ptr is the name of our variable (just as k was the name of our integer variable). The '*' informs the compiler that we
want a pointer variable, i.e. to set aside however many bytes is required to store an address in memory. The int says
that we intend to use our pointer variable to store the address of an integer. Such a pointer is said to "point to" an
integer. However, note that when we wrote int k; we did not give k a value. If this definition is made outside of any
function ANSI compliant compilers will initialize it to zero. Similarly, ptr has no value, that is we haven't stored an
address in it in the above declaration. In this case, again if the declaration is outside of any function, it is initialized
to a value guaranteed in such a way that it is guaranteed to not point to any C object or function. A pointer initialized
in this manner is called a "null" pointer.
The actual bit pattern used for a null pointer may or may not evaluate to zero since it depends on the specific system
on which the code is developed. To make the source code compatible between various compilers on various systems,
a macro is used to represent a null pointer. That macro goes under the name NULL. Thus, setting the value of a
pointer using the NULL macro, as with an assignment statement such as ptr = NULL, guarantees that the pointer has
become a null pointer. Similarly, just as one can test for an integer value of zero, as in if(k == 0), we can test for a
null pointer using if (ptr == NULL).
But, back to using our new variable ptr. Suppose now that we want to store in ptr the address of our integer variable
k. To do this we use the unary & operator and write:
ptr = &k;
What the & operator does is retrieve the lvalue (address) of k, even though k is on the right hand side of the
assignment operator '=', and copies that to the contents of our pointer ptr. Now, ptr is said to "point to" k. Bear with
us now, there is only one more operator we need to discuss.
One way to see how all this stuff fits together would be to run the following program and then review the code and
the output carefully.
------------ Program 1.1 ---------------------------------
/* Program 1.1*/
#include <stdio.h>
int j, k;
int *ptr;
int main(void)
{
j = 1;
k = 2;
ptr = &k;
printf("\n");
printf("j has the value %d and is stored at %p\n", j, (void *)&j);
printf("k has the value %d and is stored at %p\n", k, (void *)&k);
printf("ptr has the value %p and is stored at %p\n", ptr, (void *)&ptr);
printf("The value of the integer pointed to by ptr is %d\n", *ptr);
return 0;
}
Note: We have yet to discuss those aspects of C which require the use of the (void *) expression used here. For now,
include it in your test code. We'll explain the reason behind this expression later.
To review:
A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where the asterisk tells the
compiler that the variable named ptr is a pointer variable and the type tells the compiler what type the
pointer is to point to (integer in this case).
Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in
&k.
We can "dereference" a pointer, i.e. refer to the value of that which it points to, by using the unary '*'
operator as in *ptr.
An "lvalue" of a variable is the value of its address, i.e. where it is stored in memory. The "rvalue" of a
variable is the value stored in that variable (at that address).
Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore lets say that integer is
located at memory location 100 (decimal). What happens when we write:
ptr + 1;
Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it points to an integer (its current
address, 100, is the address of an integer), it adds 2 to ptr instead of 1, so the pointer "points to" the next integer, at
memory location 102. Similarly, were the ptr declared as a pointer to a long, it would add 4 to it instead of 1. The
same goes for other data types such as floats, doubles, or even user defined data types such as structures. This is
obviously not the same kind of "addition" that we normally think of. In C it is referred to as addition using "pointer
arithmetic", a term which we will come back to later.
Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is
incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post-, increments
the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 2 for an
integer, 4 for a long, etc.).
Since a block of 10 integers located contiguously in memory is, by definition, an array of integers, this brings up an
interesting relationship between arrays and pointers.
/* Program 2.1*/
#include <stdio.h>
int main(void)
{
int i;
ptr = &my_array[0]; /* point our pointer to the first
element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */
printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */
}
return 0;
}
Compile and run the above program and carefully note lines A and B and that the program prints out the same values
in either case. Also observe how we dereferenced our pointer in line B, i.e. we first added i to it and then
dereferenced the new pointer. Change line B to read:
printf("ptr + %d = %d\n",i, *ptr++);
and run it again... then change it to:
printf("ptr + %d = %d\n",i, *(++ptr));
and try once more. Each time try and predict the outcome and carefully look at the actual outcome.
In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name, thus in our
code where we wrote:
ptr = &my_array[0];
we can write:
ptr = my_array;
to achieve the same result.
This leads many texts to state that the name of an array is a pointer. I prefer to mentally think "the name of the array
is the address of first element in the array". Many beginners (including myself when I was learning) have a tendency
to become confused by thinking of it as a pointer. For example, while we can write
ptr = my_array;
we cannot write
my_array = ptr;
The reason is that while ptr is a variable, my_array is a constant. That is, the location at which the first element of
my_array will be stored cannot be changed once my_array[] has been declared.
Earlier when discussing the term "lvalue" I cited K&R-2 where it stated:
"An object is a named region of storage; an lvalue is an expression referring to an object".
This raises an interesting problem. Since my_array is a named region of storage, why is my_array in the above
assignment statement not an lvalue? To resolve this problem, some refer to my_array as an "unmodifiable lvalue".
Now, let's delve a little further into the difference between the names ptr and my_array as used above. Some writers
will refer to an array's name as a constant pointer. What do we mean by that? Well, to understand the term "constant"
in this sense, let's go back to our definition of the term "variable". When we declare a variable we set aside a spot in
memory to hold the value of the appropriate type. Once that is done the name of the variable can be interpreted in
one of two ways. When used on the left side of the assignment operator, the compiler interprets it as the memory
location to which to move that value resulting from evaluation of the right side of the assignment operator. But,
when used on the right side of the assignment operator, the name of a variable is interpreted to mean the contents
stored at that memory address set aside to hold the value of that variable.
With that in mind, let's now consider the simplest of constants, as in:
int i, k;
i = 2;
Here, while i is a variable and then occupies space in the data portion of memory, 2 is a constant and, as such,
instead of setting aside memory in the data segment, it is imbedded directly in the code segment of memory. That is,
while writing something like k = i; tells the compiler to create code which at run time will look at memory location
&i to determine the value to be moved to k, code created by i = 2; simply puts the 2 in the code and there is no
referencing of the data segment. That is, both k and i are objects, but 2 is not an object.
Similarly, in the above, since my_array is a constant, once the compiler establishes where the array itself is to be
stored, it "knows" the address of my_array[0] and on seeing:
ptr = my_array;
it simply uses this address as a constant in the code segment and there is no referencing of the data segment beyond
that.
This might be a good place explain further the use of the (void *) expression used in Program 1.1 of Chapter 1. As
we have seen we can have pointers of various types. So far we have discussed pointers to integers and pointers to
characters. In coming chapters we will be learning about pointers to structures and even pointer to pointers.
Also we have learned that on different systems the size of a pointer can vary. As it turns out it is also possible that
the size of a pointer can vary depending on the data type of the object to which it points. Thus, as with integers
where you can run into trouble attempting to assign a long integer to a variable of type short integer, you can run
into trouble attempting to assign the values of pointers of various types to pointer variables of other types.
To minimize this problem, C provides for a pointer of type void. We can declare such a pointer by writing:
void *vptr;
A void pointer is sort of a generic pointer. For example, while C will not permit the comparison of a pointer to type
integer with a pointer to type character, for example, either of these can be compared to a void pointer. Of course, as
with other variables, casts can be used to convert from one type of pointer to another under the proper
circumstances. In Program 1.1. of Chapter 1 I cast the pointers to integers into void pointers to make them
compatible with the %p conversion specification. In later chapters other casts will be made for reasons defined
therein.
Well, that's a lot of technical stuff to digest and I don't expect a beginner to understand all of it on first reading. With
time and experimentation you will want to come back and re-read the first 2 chapters. But for now, let's move on to
the relationship between pointers, character arrays, and strings.
Continue with Pointer
CHAPTER 3: Pointers and Strings
The study of strings is useful to further tie in the relationship between pointers and arrays. It also makes it easy to
illustrate how some of the standard C string functions can be implemented. Finally it illustrates how and when
pointers can and should be passed to functions.
In C, strings are arrays of characters. This is not necessarily true in other languages. In BASIC, Pascal, Fortran and
various other languages, a string has its own data type. But in C it does not. In C a string is an array of characters
terminated with a binary zero character (written as '\0'). To start off our discussion we will write some code which,
while preferred for illustrative purposes, you would probably never write in an actual program. Consider, for
example:
char my_string[40];
my_string[0] = 'T';
my_string[1] = 'e';
my_string[2] = 'd':
my_string[3] = '\0';
While one would never build a string like this, the end result is a string in that it is an array of characters terminated
with a nul character. By definition, in C, a string is an array of characters terminated with the nul character. Be aware
that "nul" is not the same as "NULL". The nul refers to a zero as defined by the escape sequence '\0'. That is it
occupies one byte of memory. NULL, on the other hand, is the name of the macro used to initialize null pointers.
NULL is #defined in a header file in your C compiler, nul may not be #defined at all.
Since writing the above code would be very time consuming, C permits two alternate ways of achieving the same
thing. First, one might write:
char my_string[40] = {'T', 'e', 'd', '\0',};
But this also takes more typing than is convenient. So, C permits:
char my_string[40] = "Ted";
When the double quotes are used, instead of the single quotes as was done in the previous examples, the nul
character ( '\0' ) is automatically appended to the end of the string.
In all of the above cases, the same thing happens. The compiler sets aside an contiguous block of memory 40 bytes
long to hold characters and initialized it such that the first 4 characters are Ted\0.
/* Program 3.1*/
#include <stdio.h>
int main(void)
{
Now, moving into the code, we declare two character pointers and show the string on the screen. We then "point" the
pointer pA at strA. That is, by means of the assignment statement we copy the address of strA[0] into our variable
pA. We now use puts() to show that which is pointed to by pA on the screen. Consider here that the function
prototype for puts() is:
int puts(const char *s);
For the moment, ignore the const. The parameter passed to puts() is a pointer, that is the value of a pointer (since all
parameters in C are passed by value), and the value of a pointer is the address to which it points, or, simply, an
address. Thus when we write puts(strA); as we have seen, we are passing the address of strA[0].
Similarly, when we write puts(pA); we are passing the same address, since we have set pA = strA;
Given that, follow the code down to the while() statement on line A. Line A states:
While the character pointed to by pA (i.e. *pA) is not a nul character (i.e. the terminating '\0'), do the following:
Line B states: copy the character pointed to by pA to the space pointed to by pB, then increment pA so it points to
the next character and pB so it points to the next space.
When we have copied the last character, pA now points to the terminating nul character and the loop ends. However,
we have not copied the nul character. And, by definition a string in C must be nul terminated. So, we add the nul
character with line C.
It is very educational to run this program with your debugger while watching strA, strB, pA and pB and single
stepping through the program. It is even more educational if instead of simply defining strB[] as has been done
above, initialize it also with something like:
strB[80] = "12345678901234567890123456789012345678901234567890"
where the number of digits used is greater than the length of strA and then repeat the single stepping procedure
while watching the above variables. Give these things a try!
Getting back to the prototype for puts() for a moment, the "const" used as a parameter modifier informs the user that
the function will not modify the string pointed to by s, i.e. it will treat that string as a constant.
Of course, what the above program illustrates is a simple way of copying a string. After playing with the above until
you have a good understanding of what is happening, we can proceed to creating our own replacement for the
standard strcpy() that comes with C. It might look like:
char *my_strcpy(char *destination, char *source)
{
char *p = destination;
while (*source != '\0')
{
*p++ = *source++;
}
*p = '\0';
return destination;
}
In this case, I have followed the practice used in the standard routine of returning a pointer to the destination.
Again, the function is designed to accept the values of two character pointers, i.e. addresses, and thus in the previous
program we could write:
int main(void)
{
my_strcpy(strB, strA);
puts(strB);
}
I have deviated slightly from the form used in standard C which would have
the prototype:
char *my_strcpy(char *destination, const char *source);
Here the "const" modifier is used to assure the user that the function will not modify the contents pointed to by the
source pointer. You can prove this by modifying the function above, and its prototype, to include the "const"
modifier as shown. Then, within the function you can add a statement which attempts to change the contents of that
which is pointed to by source, such as:
*source = 'X';
which would normally change the first character of the string to an X. The const modifier should cause your
compiler to catch this as an error. Try it and see.
Now, let's consider some of the things the above examples have shown us. First off, consider the fact that *ptr++ is
to be interpreted as returning the value pointed to by ptr and then incrementing the pointer value. This has to do with
the precedence of the operators. Were we to write (*ptr)++ we would increment, not the pointer, but that which the
pointer points to! i.e. if used on the first character of the above example string the 'T' would be incremented to a 'U'.
You can write some simple example code to illustrate this.
Recall again that a string is nothing more than an array of characters, with the last character being a '\0'. What we
have done above is deal with copying an array. It happens to be an array of characters but the technique could be
applied to an array of integers, doubles, etc. In those cases, however, we would not be dealing with strings and hence
the end of the array would not be marked with a special value like the nul character. We could implement a version
that relied on a special value to identify the end. For example, we could copy an array of positive integers by
marking the end with a negative integer. On the other hand, it is more usual that when we write a function to copy an
array of items other than strings we pass the function the number of items to be copied as well as the address of the
array, e.g. something like the following prototype might indicate:
void int_copy(int *ptrA, int *ptrB, int nbr);
where nbr is the number of integers to be copied. You might want to play with this idea and create an array of
integers and see if you can write the function int_copy() and make it work.
This permits using functions to manipulate large arrays. For example, if we have an array of 5000 integers that we
want to manipulate with a function, we need only pass to that function the address of the array (and any auxiliary
information such as nbr above, depending on what we are doing). The array itself does not get passed, i.e. the whole
array is not copied and put on the stack before calling the function, only its address is sent.
This is different from passing, say an integer, to a function. When we pass an integer we make a copy of the integer,
i.e. get its value and put it on the stack. Within the function any manipulation of the value passed can in no way
effect the original integer. But, with arrays and pointers we can pass the address of the variable and hence
manipulate the values of the original variables.
Since parameters are passed by value, in both the passing of a character pointer or the name of the array as above,
what actually gets passed is the address of the first element of each array. Thus, the numerical value of the parameter
passed is the same whether we use a character pointer or an array name as a parameter. This would tend to imply
that somehow source[i] is the same as *(p+i).
In fact, this is true, i.e wherever one writes a[i] it can be replaced with *(a + i) without any problems. In fact, the
compiler will create the same code in either case. Thus we see that pointer arithmetic is the same thing as array
indexing. Either syntax produces the same result.
This is NOT saying that pointers and arrays are the same thing, they are not. We are only saying that to identify a
given element of an array we have the choice of two syntaxes, one using array indexing and the other using pointer
arithmetic, which yield identical results.
Now, looking at this last expression, part of it.. (a + i), is a simple addition using the + operator and the rules of C
state that such an expression is commutative. That is (a + i) is identical to (i + a). Thus we could write *(i + a) just as
easily as *(a + i).
But *(i + a) could have come from i[a] ! From all of this comes the curious truth that if:
char a[20];
int i;
writing
a[3] = 'x';
is the same as writing
3[a] = 'x';
Try it! Set up an array of characters, integers or longs, etc. and assigned the 3rd or 4th element a value using the
conventional approach and then print out that value to be sure you have that working. Then reverse the array
notation as I have done above. A good compiler will not balk and the results will be identical. A curiosity... nothing
more!
At this point you might want to experiment a bit with writing some of your own programs using pointers.
Manipulating strings is a good place to experiment. You might want to write your own versions of such standard
functions as:
strlen();
strcat();
strchr();
and any others you might have on your system.
We will come back to strings and their manipulation through pointers in a future chapter. For now, let's move on and
discuss structures for a bit.
Let's say we have a bunch of these structures in a disk file and we want to read each one out and print out the first
and last name of each one so that we can have a list of the people in our files. The remaining information will not be
printed out. We will want to do this printing with a function call and pass to that function a pointer to the structure at
hand. For demonstration purposes I will use only one structure for now. But realize the goal is the writing of the
function, not the reading of the file which, presumably, we know how to do.
For review, recall that we can access structure members with the dot operator as in:
--------------- program 5.1 ------------------
/* Program 5.1*/
#include <stdio.h>
#include <string.h>
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
int main(void)
{
strcpy(my_struct.lname,"Jensen");
strcpy(my_struct.fname,"Ted");
printf("\n%s ",my_struct.fname);
printf("%s\n",my_struct.lname);
return 0;
}
Anyway, if we pass the whole structure it means that we must copy the contents of the structure from the calling
function to the called function. In systems using stacks, this is done by pushing the contents of the structure on the
stack. With large structures this could prove to be a problem. However, passing a pointer uses a minimum amount of
stack space.
In any case, since this is a discussion of pointers, we will discuss how we go about passing a pointer to a structure
and then using it within the function.
Consider the case described, i.e. we want a function that will accept as a parameter a pointer to a structure and from
within that function we want to access members of the structure. For example we want to print out the name of the
employee in our example structure.
Okay, so we know that our pointer is going to point to a structure declared using struct tag. We declare such a
pointer with the declaration:
struct tag *st_ptr;
and we point it to our example structure with:
st_ptr = &my_struct;
Now, we can access a given member by de-referencing the pointer. But, how do we de-reference the pointer to a
structure? Well, consider the fact that we might want to use the pointer to set the age of the employee. We would
write:
(*st_ptr).age = 63;
Look at this carefully. It says, replace that within the parenthesis with that which st_ptr points to, which is the
structure my_struct. Thus, this breaks down to the same as my_struct.age.
However, this is a fairly often used expression and the designers of C have created an alternate syntax with the same
meaning which is:
st_ptr->age = 63;
With that in mind, look at the following program:
------------ program 5.2 ---------------------
/* Program 5.2*/
#include <stdio.h>
#include <string.h>
int main(void)
{
struct tag *st_ptr; /* a pointer to a structure */
st_ptr = &my_struct; /* point the pointer to my_struct */
strcpy(my_struct.lname,"Jensen");
strcpy(my_struct.fname,"Ted");
printf("\n%s ",my_struct.fname);
printf("%s\n",my_struct.lname);
my_struct.age = 63;
show_name(st_ptr); /* pass the pointer */
return 0;
}
Actually, if all we wanted to do was store the name "Ted" we could write:
char my_name[] = "Ted";
and the compiler would count the characters, leave room for the nul character and store the total of the four
characters in memory the location of which would be returned by the array name, in this case my_name.
In the array notation, my_name is short for &myname[0] which is the address of the first element of the array. Since
the location of the array is fixed during run time, this is a constant (not a variable). In the pointer notation my_name
is a variable. As to which is the better method, that depends on what you are going to do within the rest of the
program.
Let's now go one step further and consider what happens if each of these declarations are done within a function as
opposed to globally outside the bounds of any function.
void my_function_A(char *ptr)
{
char a[] = "ABCDE"
.
.
}
By the way, array initialization of automatic variables as I have done in my_function_A was illegal in the older
K&R C and only "came of age" in the newer ANSI C. A fact that may be important when one is considering
portability and backwards compatibility.
As long as we are discussing the relationship/differences between pointers and arrays, let's move on to multi-
dimensional arrays. Consider, for example the array:
char multi[5][10];
Just what does this mean? Well, let's consider it in the following light.
char multi[5][10];
Let's take the underlined part to be the "name" of an array. Then prepending the char and appending the [10] we
have an array of 10 characters. But, the name multi[5] is itself an array indicating that there are 5 elements each
being an array of 10 characters. Hence we have an array of 5 arrays of 10 characters each..
Assume we have filled this two dimensional array with data of some kind. In memory, it might look as if it had been
formed by initializing 5 separate arrays using something like:
multi[0] = {'0','1','2','3','4','5','6','7','8','9'}
multi[1] = {'a','b','c','d','e','f','g','h','i','j'}
multi[2] = {'A','B','C','D','E','F','G','H','I','J'}
multi[3] = {'9','8','7','6','5','4','3','2','1','0'}
multi[4] = {'J','I','H','G','F','E','D','C','B','A'}
At the same time, individual elements might be addressable using syntax such as:
multi[0][3] = '3'
multi[1][7] = 'h'
multi[4][0] = 'J'
Since arrays are contiguous in memory, our actual memory block for the above should look like:
0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA
^
|_____ starting at the address &multi[0][0]
Note that I did not write multi[0] = "0123456789". Had I done so a terminating '\0' would have been implied since
whenever double quotes are used a '\0' character is appended to the characters contained within those quotes. Had
that been the case I would have had to set aside room for 11 characters per row instead of 10.
My goal in the above is to illustrate how memory is laid out for 2 dimensional arrays. That is, this is a 2 dimensional
array of characters, NOT an array of "strings".
Now, the compiler knows how many columns are present in the array so it can interpret multi + 1 as the address of
the 'a' in the 2nd row above. That is, it adds 10, the number of columns, to get this location. If we were dealing with
integers and an array with the same dimension the compiler would add 10*sizeof(int) which, on my machine, would
be 20. Thus, the address of the 9 in the 4th row above would be &multi[3][0] or *(multi + 3) in pointer notation. To
get to the content of the 2nd element in the 4th row we add 1 to this address and dereference the result as in
*(*(multi + 3) + 1)
With a little thought we can see that:
*(*(multi + row) + col) and
multi[row][col] yield the same results.
The following program illustrates this using integer arrays instead of character arrays.
------------------- program 6.1 ----------------------
/* Program 6.1*/
#include <stdio.h>
#define ROWS 5
#define COLS 10
int multi[ROWS][COLS];
int main(void)
{
int row, col;
for (row = 0; row < ROWS; row++)
{
for (col = 0; col < COLS; col++)
{
multi[row][col] = row*col;
}
}
return 0;
}
----------------- end of program 6.1 ---------------------
Because of the double de-referencing required in the pointer version, the name of a 2 dimensional array is often said
to be equivalent to a pointer to a pointer. With a three dimensional array we would be dealing with an array of arrays
of arrays and some might say its name would be equivalent to a pointer to a pointer to a pointer. However, here we
have initially set aside the block of memory for the array by defining it using array notation. Hence, we are dealing
with a constant, not a variable. That is we are talking about a fixed address not a variable pointer. The dereferencing
function used above permits us to access any element in the array of arrays without the need of changing the value
of that address (the address of multi[0][0] as given by the symbol multi).
int multi[ROWS][COLS];
we can access individual elements of the array multi using either:
multi[row][col]
or
*(*(multi + row) + col)
To understand more fully what is going on, let us replace
*(multi + row)
with X as in:
*(X + col)
Now, from this we see that X is like a pointer since the expression is de-referenced and we know that col is an
integer. Here the arithmetic being used is of a special kind called "pointer arithmetic" is being used. That means that,
since we are talking about an integer array, the address pointed to by (i.e. value of) X + col + 1 must be greater than
the address X + col by and amount equal to sizeof(int).
Since we know the memory layout for 2 dimensional arrays, we can determine that in the expression multi + row as
used above, multi + row + 1 must increase by value an amount equal to that needed to "point to" the next row, which
in this case would be an amount equal to COLS * sizeof(int).
That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run time, the compiler must
generate code which takes into consideration the value of COLS, i.e. the 2nd dimension. Because of the equivalence
of the two forms of expression, this is true whether we are using the pointer expression as here or the array
expression multi[row][col].
1. The address of the first element of the array, which is returned by the expression multi, i.e., the name of the
array.
2. The size of the type of the elements of the array, in this case sizeof(int).
3. The 2nd dimension of the array
4. The specific index value for the first dimension, row in this case.
5. The specific index value for the second dimension, col in this case.
Given all of that, consider the problem of designing a function to manipulate the element values of a previously
declared array. For example, one which would set all the elements of the array multi to the value 1.
void set_value(int m_array[][COLS])
{
int row, col;
for (row = 0; row < ROWS; row++)
{
for (col = 0; col < COLS; col++)
{
m_array[row][col] = 1;
}
}
}
And to call this function we would then use:
set_value(multi);
Now, within the function we have used the values #defined by ROWS and COLS that set the limits on the for loops.
But, these #defines are just constants as far as the compiler is concerned, i.e. there is nothing to connect them to the
array size within the function. row and col are local variables, of course. The formal parameter definition permits the
compiler to determine the characteristics associated with the pointer value that will be passed at run time. We really
don’t need the first dimension and, as will be seen later, there are occasions where we would prefer not to define it
within the parameter definition, out of habit or consistency, I have not used it here. But, the second dimension must
be used as has been shown in the expression for the parameter. The reason is that we need this in the evaluation of
m_array[row][col] as has been described. While the parameter defines the data type (int in this case) and the
automatic variables for row and column are defined in the for loops, only one value can be passed using a single
parameter. In this case, that is the value of multi as noted in the call statement, i.e. the address of the first element,
often referred to as a pointer to the array. Thus, the only way we have of informing the compiler of the 2nd
dimension is by explicitly including it in the parameter definition.
In fact, in general all dimensions of higher order than one are needed when dealing with multi-dimensional arrays.
That is if we are talking about 3 dimensional arrays, the 2nd and 3rd dimension must be specified in the parameter
definition.
To review, in Chapter 2 we stated that given an array of integers we could point an integer pointer at that array
using:
int *ptr;
ptr = &my_array[0]; /* point our pointer at the first
integer in our array */
As we stated there, the type of the pointer variable must match the type of the first element of the array.
In addition, we can use a pointer as a formal parameter of a function which is designed to manipulate an array. e.g.
Given:
int array[3] = {'1', '5', '7'};
void a_func(int *p);
Some programmers might prefer to write the function prototype as:
void a_func(int p[]);
which would tend to inform others who might use this function that the function is designed to manipulate the
elements of an array. Of course, in either case, what actually gets passed is the value of a pointer to the first element
of the array, independent of which notation is used in the function prototype or definition. Note that if the array
notation is used, there is no need to pass the actual dimension of the array since we are not passing the whole array,
only the address to the first element.
We now turn to the problem of the 2 dimensional array. As stated in the last chapter, C interprets a 2 dimensional
array as an array of one dimensional arrays. That being the case, the first element of a 2 dimensional array of
integers is a one dimensional array of integers. And a pointer to a two dimensional array of integers must be a
pointer to that data type. One way of accomplishing this is through the use of the keyword "typedef". typedef assigns
a new name to a specified data type. For example:
typedef unsigned char byte;
causes the name byte to mean type unsigned char. Hence
byte b[10]; would be an array of unsigned characters.
Note that in the typedef declaration, the word byte has replaced that which would normally be the name of our
unsigned char. That is, the rule for using typedef is that the new name for the data type is the name used in the
definition of the data type. Thus in:
typedef int Array[10];
Array becomes a data type for an array of 10 integers. i.e. Array my_arr; declares my_arr as an array of 10 integers
and Array arr2d[5]; makes arr2d an array of 5 arrays of 10 integers each.
Also note that Array *p1d; makes p1d a pointer to an array of 10 integers. Because *p1d points to the same type as
arr2d, assigning the address of the two dimensional array arr2d to p1d, the pointer to a one dimensional array of 10
integers is acceptable. i.e. p1d = &arr2d[0]; or p1d = arr2d; are both correct.
Since the data type we use for our pointer is an array of 10 integers we would expect that incrementing p1d by 1
would change its value by 10*sizeof(int), which it does. That is, sizeof(*p1d) is 20. You can prove this to yourself
by writing and running a simple short program.
Now, while using typedef makes things clearer for the reader and easier on the programmer, it is not really
necessary. What we need is a way of declaring a pointer like p1d without the need of the typedef keyword. It turns
out that this can be done and that
int (*p1d)[10];
is the proper declaration, i.e. p1d here is a pointer to an array of 10 integers just as it was under the declaration using
the Array type. Note that this is different from
int *p1d[10];
which would make p1d the name of an array of 10 pointers to type int.
When memory is allocated, the allocating function (such as malloc(), calloc(), etc.) returns a pointer. The type of this
pointer depends on whether you are using an older K&R compiler or the newer ANSI type compiler. With the older
compiler the type of the returned pointer is char, with the ANSI compiler it is void.
If you are using an older compiler, and you want to allocate memory for an array of integers you will have to cast
the char pointer returned to an integer pointer. For example, to allocate space for 10 integers we might write:
int *iptr;
iptr = (int *)malloc(10 * sizeof(int));
if (iptr == NULL)
Because of the equivalence between array and pointer notation, once iptr has been assigned as above, one can use
the array notation. For example, one could write:
int k;
for (k = 0; k < 10; k++)
iptr[k] = 2;
to set the values of all elements to 2.
Even with a reasonably good understanding of pointers and arrays, one place the newcomer to C is likely to stumble
at first is in the dynamic allocation of multi-dimensional arrays. In general, we would like to be able to access
elements of such arrays using array notation, not pointer notation, wherever possible. Depending on the application
we may or may not know both dimensions at compile time. This leads to a variety of ways to go about our task.
As we have seen, when dynamically allocating a one dimensional array its dimension can be determined at run time.
Now, when using dynamic allocation of higher order arrays, we never need to know the first dimension at compile
time. Whether we need to know the higher dimensions depends on how we go about writing the code. Here I will
discuss various methods of dynamically allocating room for 2 dimensional arrays of integers.
First we will consider cases where the 2nd dimension is known at compile time.
METHOD 1:
One way of dealing with the problem is through the use of the typedef keyword. To allocate a 2 dimensional array of
integers recall that the following two notations result in the same object code being generated:
multi[row][col] = 1; *(*(multi + row) + col) = 1;
It is also true that the following two notations generate the same code:
multi[row] *(multi + row)
Since the one on the right must evaluate to a pointer, the array notation on the left must also evaluate to a pointer. In
fact multi[0] will return a pointer to the first integer in the first row, multi[1] a pointer to the first integer of the
second row, etc. Actually, multi[n] evaluates to a pointer to that array of integers that make up the n-th row of our 2
dimensional array. That is, multi can be thought of as an array of arrays and multi[n] as a pointer to the n-th array of
this array of arrays. Here the word pointer is being used to represent an address value. While such usage is common
in the literature, when reading such statements one must be careful to distinguish between the constant address of an
array and a variable pointer which is a data object in itself.
Consider now:
--------------- Program 9.1 --------------------------------
/* Program 9.1*/
#include <stdio.h>
#include <stdlib.h>
#define COLS 5
int main(void)
{
int nrows = 10;
int row, col;
rptr = malloc(nrows * COLS * sizeof(int));
for (row = 0; row < nrows; row++)
{
for (col = 0; col < COLS; col++)
{
rptr[row][col] = 17;
}
}
return 0;
}
------------- End of Prog. 9.1 --------------------------------
Here I have assumed an ANSI compiler so a cast on the void pointer returned by malloc() is not required. If you are
using an older K&R compiler you will have to cast using:
rptr = (RowArray *)malloc(.... etc.
Using this approach, rptr has all the characteristics of an array name name, (except that rptr is modifiable), and array
notation may be used throughout the rest of the program. That also means that if you intend to write a function to
modify the array contents, you must use COLS as a part of the formal parameter in that function, just as we did
when discussing the passing of two dimensional arrays to a function.
METHOD 2:
In the METHOD 1 above, rptr turned out to be a pointer to type "one dimensional array of COLS integers". It turns
out that there is syntax which can be used for this type without the need of typedef. If we write:
int (*xptr)[COLS];
the variable xptr will have all the same characteristics as the variable rptr in METHOD 1 above, and we need not use
the typedef keyword. Here xptr is a pointer to an array of integers and the size of that array is given by the #defined
COLS. The parenthesis placement makes the pointer notation predominate, even though the array notation has
higher precedence. i.e. had we written
int *xptr[COLS];
we would have defined xptr as an array of pointers holding the number of pointers equal to that #defined by COLS.
That is not the same thing at all. However, arrays of pointers have their use in the dynamic allocation of two
dimensional arrays, as will be seen in the next 2 methods.
METHOD 3:
Consider the case where we do not know the number of elements in each row at compile time, i.e. both the number
of rows and number of columns must be determined at run time. One way of doing this would be to create an array
of pointers to type int and then allocate space for each row and point these pointers at each row. Consider:
-------------- Program 9.2 ------------------------------------
/* Program 9.2 */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int nrows = 5; /* Both nrows and ncols could be evaluated */
int ncols = 10; /* or read in at run time */
int row;
int **rowptr;
rowptr = malloc(nrows * sizeof(int *));
if (rowptr == NULL)
{
puts("\nFailure to allocate room for row pointers.\n");
exit(0);
}
return 0;
}
You can, however, use the array notation just as if it were a continuous block of memory. For example, you can
write:
rowptr[row][col] = 176;
just as if rowptr were the name of a two dimensional array created at compile time. Of course row and col must be
within the bounds of the array you have created, just as with an array created at compile time.
If you want to have a contiguous block of memory dedicated to the storage of the elements in the array you can do it
as follows:
METHOD 4:
In this method we allocate a block of memory to hold the whole array first. We then create an array of pointers to
point to each row. Thus even though the array of pointers is being used, the actual array in memory is contiguous.
The code looks like this:
----------------- Program 9.3 -----------------------------------
/* Program 9.3*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int **rptr;
int *aptr;
int *testptr;
int k;
int nrows = 5; /* Both nrows and ncols could be evaluated */
int ncols = 8; /* or read in at run time */
int row, col;
puts("\n");
testptr = aptr;
for (row = 0; row < nrows; row++)
{
for (col = 0; col < ncols; col++)
{
printf("%d ", *(testptr++));
}
putchar('\n');
}
return 0;
}
As a final example on multidimensional arrays we will illustrate the dynamic allocation of a three dimensional array.
This example will illustrate one more thing to watch when doing this kind of allocation. For reasons cited above we
will use the approach outlined in alternative two. Consider the following code:
------------------- Program 9.4 -------------------------------------
/* Program 9.4*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
int X_DIM=16;
int Y_DIM=5;
int Z_DIM=3;
int main(void)
{
char *space;
char ***Arr3D;
int y, z;
ptrdiff_t diff;
Consider the following real problem. You want to write a function that is capable of sorting virtually any collection
of data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The
sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more
complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes.
Sedgewick [1] has described the bubble sort using C code by setting up a function which when passed a pointer to
the array would sort it. If we call that function bubble(), a sort program is described by bubble_1.c, which follows:
/*-------------------- bubble_1.c --------------------*/
/* Program bubble_1.c*/
#include <stdio.h>
int main(void)
{
int i;
putchar('\n');
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
bubble(arr,10);
putchar('\n');
Here our function is designed to sort an array of integers. Thus in line 1 we are comparing integers and in lines 2
through 4 we are using temporary integer storage to store integers. What we want to do now is see if we can convert
this code so we can use any data type, i.e. not be restricted to integers.
At the same time we don't want to have to analyze our algorithm and the code associated with it each time we use it.
We start by removing the comparison from within the function bubble() so as to make it relatively easy to modify
the comparison function without having to re-write portions related to the actual algorithm. This results in
bubble_2.c:
/*---------------------- bubble_2.c -------------------------*/
/* Program bubble_2.c*/
#include <stdio.h>
int main(void)
{
int i;
putchar('\n');
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
bubble(arr,10);
putchar('\n');
{
int i, j, t;
for (i = N-1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (compare(a[j-1], a[j]))
{
t = a[j-1];
a[j-1] = a[j];
a[j] = t;
}
}
}
}
/* Program bubble_3.c*/
#include <stdio.h>
int main(void)
{
int i;
putchar('\n');
/* Program bubble_4.c*/
#include <stdio.h>
int main(void)
{
int i;
putchar('\n');
We now address the problem of what we pass to bubble(). We want to make the first parameter of that function a
void pointer also. But, that means that within bubble() we need to do something about the variable t, which is
currently an integer. Also, where we use t = p[j-1]; the type of p[j-1] needs to be known in order to know how many
bytes to copy to the variable t (or whatever we replace t with).
Currently, in bubble_4.c, knowledge within bubble() as to the type of the data being sorted (and hence the size of
each individual element) is obtained from the fact that the first parameter is a pointer to type integer. If we are going
to be able to use bubble() to sort any type of data, we need to make that pointer a pointer to type void. But, in doing
so we are going to lose information concerning the size of individual elements within the array. So, in bubble_5.c we
will add a separate parameter to handle this size information.
These changes, from bubble4.c to bubble5.c are, perhaps, a bit more extensive than those we have made in the past.
So, compare the two modules carefully for differences.
/*---------------------- bubble5.c ---------------------------*/
/* Program bubble_5.c*/
#include <stdio.h>
#include <string.h>
int main(void)
{
int i;
putchar('\n');
return 0;
}
We also had to modify what we passed to compare(), and how we do the swapping of elements that the comparison
indicates need swapping. Use of memcpy() and pointer notation instead of array notation work towards this
reduction in type sensitivity.
Again, making a careful comparison of bubble5.c with bubble4.c can result in improved understanding of what is
happening and why.
We move now to bubble6.c where we use the same function bubble() that we used in bubble5.c to sort strings
instead of long integers. Of course we have to change the comparison function since the means by which strings are
compared is different from that by which long integers are compared. And,in bubble6.c we have deleted the lines
within bubble() that were commented out in bubble5.c.
/*--------------------- bubble6.c ---------------------*/
/* Program bubble_6.c*/
#include <stdio.h>
#include <string.h>
"Donald Duck",
"Minnie Mouse",
"Goofy",
"Ted Jensen" };
int main(void)
{
int i;
putchar('\n');
Pointers to functions must match the functions pointed to in the number and types of the parameters and the type of
the return value. In our case, we declare our function pointer as:
int (*fptr)(const void *p1, const void *p2);
Note that were we to write:
int *fptr(const void *p1, const void *p2);
we would have a function prototype for a function which returned a pointer to type int. That is because in C the
parenthesis () operator have a higher precedence than the pointer * operator. By putting the parenthesis around the
string (*fptr) we indicate that we are declaring a function pointer.
We now modify our declaration of bubble() by adding, as its 4th parameter, a function pointer of the proper type. It's
function prototype becomes:
void bubble(void *p, int width, int N,
int(*fptr)(const void *, const void *));
When we call the bubble(), we insert the name of the comparison function that we want to use. bubble7.c illustrate
how this approach permits the use of the same bubble() function for sorting different types of data.
/*------------------- bubble7.c ------------------*/
/* Program bubble_7.c*/
#include <stdio.h>
#include <string.h>
int main(void)
{
int i;
puts("\nBefore Sorting:\n");
1. "Algorithms in C"
Robert Sedgewick
Addison-Wesley
ISBN 0-201-51425-7.
---*--- End of Pointers ---*---