c programming
Sorting
1.Bubble Sort
public static void sort(int[] a)
{
Int swapp=0;
for(int i=a.length -1;i>=0;i--)
{
for(int mass=0;mass<=i-1;mass++)
{
if(a[mass]>a[mass+1])
{
int temp=a[mass];
a[mass]=a[mass+1];
a[mass+1]=temp;
}
swapp=1;
}
if(swapp==0)
{
break;
}
}
}
2.Selection sort
void sort(int arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
4.quick sort
import java.io.*;
class quickSort
{
public static int partion(int[] a,int low,int high)
{
int pivot=a[high];
int i=low-1;
for(int j=low;j<high;j++)
{
if(a[j]<=pivot)
{
i++;
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
int temp=a[i+1];
a[i+1]=a[high];
a[high]=temp;
return i+1;
}
public static void sort(int[] a,int low,int high)
{
if(low<high)
{
int pi=partion(a,low,high);
sort(a,low,pi-1);
sort(a,pi+1,high);
}
}
public static void main(String[] args)
{
int[] a={9,8,7,6,5,4,3,2,1};
int n=a.length;
sort(a,0,n-1);
for(int i:a)
{
System.out.print(i+" ");
}
}
}
5.merge sort
import java.io.*;
class mergesort{
public static void merge(int[] a,int low,int mid,int high)
{
int[] temp=new int[high+1];
for(int i=low;i<=high;i++)
{
temp[i]=a[i];
}
int i=low;
int j=mid+1;
int k=low;
while(i<=mid && j<=high)
{
if(temp[i]<=temp[j])
{
a[k]=temp[i];
i++;
}
else
{
a[k]=temp[j];
j++;
}
k++;
}
while(i<=mid)
{
a[k]=temp[i];
i++;
k++;
}
}
public static void sort(int[] a,int low,int high )
{
if(low<high)
{
int mid=(low+high)/2;
sort(a,low,mid);
sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
public static void main(String[] args)
{
int[] a={9,8,7,65,4,3,21};
int n=a.length;
sort(a,0,n-1);
for(int i:a)
{
System.out.print(i+" ");
}
}
}
6.HeapSort
import java.io.*;
class heapsort
{
public static void sort(int[] a)
{
int n=a.length;
for(int i=n/2 -1;i>=0;i--)
{
heapify(a,n,i);
}
for(int i=n-1;i>=0;i--)
{//swap(a[i],a[0]);
int temp=a[i];
a[i]=a[0];
a[0]=temp;
heapify(a,i,0);
}
}
public static void heapify(int[] a,int n,int i)
{
int largest=i;
int l=2*i + 1;
int r=2*i + 2;
if(l<n && a[l]>a[largest])
{
largest=l;
}
if(r<n && a[r]>a[largest])
{
largest=r;
}
if(largest!=i)
{ //swap(a[i],largest);
int temp=a[i];
a[i]=a[largest];
a[largest]=temp;
heapify(a,n,largest);
}
}
public static void main(String[] args)
{
int[] a={9,8,7,6,5,4,3,2,1};
sort(a);
for(int i:a)
{
System.out.print(i+" ");
}
}
}
.........................................................................
Pointer
Void pointer
Void pointer is a specific pointer type – void * – a pointer that points to some data location in
storage, which doesn’t have any specific type.
storage, which doesn’t have any specific type.
- void pointers cannot be dereferenced.It can however be done using typecasting the voidpointer
- Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
//A void pointer
void *ptr;
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}
Output:
Integer variable is = 4
Float variable is= 5.500000
Float variable is= 5.500000
Wild pointer
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}
Note:
int main( )
{
int arr[2] = {0,1};
printf("First Element = %d\n",arr[0]);
getchar();
return 0;
}
Note:
int a[10];
int *p;
p=a; /*legal*/
a=p; /*illegal*/
int *p;
p=a; /*legal*/
a=p; /*illegal*/
5) Arithmetic on pointer variable is allowed.
p++; /*Legal*/
a++; /*illegal*/
a++; /*illegal*/
NULL Pointer
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be
assigned to a pointer, then we can simply use NULL.
assigned to a pointer, then we can simply use NULL.
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf("The value of ptr is %u", ptr);
return 0;
}
//The value of ptr is 0
Important Points
NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid
address for any member or object.
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Dangling pointer
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
// After below free call, ptr becomes a
// dangling pointer
free(ptr);
// No more a dangling pointer
ptr = NULL;
}
.........................................................................
What are near, far and huge pointers?
Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine.
The limitation is that we can only access 64kb of data at a time.
The limitation is that we can only access 64kb of data at a time.
A far pointer is typically 32 bit that can access memory outside current segment. To use this,
compiler allocates a segment register to store segment address, then another register to store offset
within current segment.
compiler allocates a segment register to store segment address, then another register to store offset
within current segment.
Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In case of far
pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can
be
pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can
be
.........................................................................
Function Pointer in C
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}
Output:
Value of a is 10
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun; // & removed
fun_ptr(10); // * removed
return 0;
}
.........................................................................
Difference between const char *p, char * const p and const char * const p
Difference between const char *p, char * const p and const char * const p
1.const char *ptr : This is a pointer to a constant character. You cannot change the value pointed
by ptr, but you can change the pointer itself. “const char *” is a (non-const) pointer to a const char.
by ptr, but you can change the pointer itself. “const char *” is a (non-const) pointer to a const char.
// C program to illustrate
// char const *p
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a ='A', b ='B';
const char *ptr = &a;
//*ptr = b; illegal statement (assignment of read-only location *ptr)
// ptr can be changed
printf( "value pointed to by ptr: %c\n", *ptr);
ptr = &b;
printf( "value pointed to by ptr: %c\n", *ptr);
}
//
value pointed to by ptr:A
value pointed to by ptr:B
value pointed to by ptr:B
Note:
There is no difference between const char *p and char const *p as both are pointer to a const
char and position of ‘*'(asterik) is also same.
char and position of ‘*'(asterik) is also same.
2.char *const ptr : This is a constant pointer to non-constant character. You cannot change the
pointer p, but can change the value pointed by ptr.
pointer p, but can change the value pointed by ptr.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a ='A', b ='B';
char *const ptr = &a;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n\n", ptr);
//ptr = &b; illegal statement (assignment of read-only variable ptr)
// changing the value at the address ptr is pointing to
*ptr = b;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n", ptr);
}
Output:
Value pointed to by ptr: A
Address ptr is pointing to: -1443150762
Value pointed to by ptr: B
Address ptr is pointing to: -1443150762
Address ptr is pointing to: -1443150762
Value pointed to by ptr: B
Address ptr is pointing to: -1443150762
3.const char * const ptr : This is a constant pointer to constant character. You can neither change
the value pointed by ptr nor the pointer ptr.
the value pointed by ptr nor the pointer ptr.
// C program to illustrate
//const char * const ptr
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a ='A', b ='B';
const char *const ptr = &a;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n\n", ptr);
// ptr = &b; illegal statement (assignment of read-only variable ptr)
// *ptr = b; illegal statement (assignment of read-only location *ptr)
}
|
Output:
Value pointed to by ptr: A
Address ptr is pointing to: -255095482
Address ptr is pointing to: -255095482
................................................................................................................................................................
Pointer to an Array | Array Pointer
Pointer to Array
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
In this program, we have a pointer ptr that points to the 0th element of the array.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different. The following program shows this:
array are totally different. The following program shows this:
// C program to understand difference between
// pointer to an integer and pointer to an
// array of integers.
#include<stdio.h>
int main()
{
// Pointer to an integer
int *p;
// Pointer to an array of 5 integers
int (*ptr)[5];
int arr[5];
// Points to 0th element of the arr.
p = arr;
// Points to the whole array arr.
ptr = &arr;
printf("p = %p, ptr = %p\n", p, ptr);
p++;
ptr++;
printf("p = %p, ptr = %p\n", p, ptr);
return 0;
}
Output:
p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50
p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64
p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64
int main()
{
int arr[] = { 3, 5, 6, 7, 9 };
int *p = arr;
int (*ptr)[5] = &arr;
printf("p = %p, ptr = %p\n", p, ptr);
printf("*p = %d, *ptr = %p\n", *p, *ptr);
printf("sizeof(p) = %lu, sizeof(*p) = %lu\n",
sizeof(p), sizeof(*p));
printf("sizeof(ptr) = %lu, sizeof(*ptr) = %lu\n",
sizeof(ptr), sizeof(*ptr));
return 0;
}
Output:
p = 0x7ffde1ee5010, ptr = 0x7ffde1ee5010
*p = 3, *ptr = 0x7ffde1ee5010
sizeof(p) = 8, sizeof(*p) = 4
sizeof(ptr) = 8, sizeof(*ptr) = 20
*p = 3, *ptr = 0x7ffde1ee5010
sizeof(p) = 8, sizeof(*p) = 4
sizeof(ptr) = 8, sizeof(*ptr) = 20
................................................................................................................................................................
Function
Address + Number=Next Address
Address - Number=Prev Address
++Address=Next Address
Address++=Next Address
--Address or Address--=previous Address
question:
#include <stdio.h>
int main() {
int i1,i2;
int *p1,*p2;
p1=&i1;
p2=&i2;
printf("\n %u",p1 + p2);
return 0;
}
//error
//error
Note:
int ptr :inc/dec=2 byte
float ptr :inc/dec=4 byte
char ptr :inc/dec=1 byte
double ptr :inc/dec=8 byte
Address1 -Adress2=No of element
..................
#include <stdio.h>
int main() {
int *p1=(int*)100;
int *p2=(int*)200;
printf("%d",p2 - p1);
return 0;
}
//25 if integer pionter of 4 byte............(200 -100)/4
Structures in C
Struct Hack
Difference between C structures and C++
structures
...................................................................................................................................................................
c and ds nitt
// of enum in C
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
Output:
1, 0, 0
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
Output:
1 2 5 6 10 11 12
#include <stdio.h>
enum State {WORKING = 0, FAILED, FREEZED};
enum State currState = 2;
enum State FindState() {
return currState;
}
int main() {
(FindState() == WORKING)? printf("WORKING"): printf("NOT WORKING");
return 0;
}
//NOT WORKING
Enum vs Macro
We can also use macros to define names constants. For example we can define
‘Working’ and ‘Failed’ using following macro.
‘Working’ and ‘Failed’ using following macro.
#define Working 0
#define Failed 1
#define Freezed 2
|
There are multiple advantages of using enum over macro when many related
named constants have integral values.
named constants have integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values. Following is simpler
enum state {Working, Failed, Freezed};
Structures in C
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
// A variable declaration like basic data types
struct Point
{
int x, y;
};
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
// Accesing members of point p1
p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;
}
Output:
20 1
/////////////////////////////////////////////////////////////////////
What is designated Initialization?
Designated Initialization allows structure members to be initialized in any order.
This feature has been added in c99 standard
This feature has been added in c99 standard
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initializtion using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);
printf ("x = %d", p2.x);
return 0;
}
|
Output:
x = 2, y = 0,
z = 1
x = 20
x = 20
///////////////////////////////////////////////////////////////////////////
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
printf("%d %d", arr[0].x, arr[0].y);
return 0;
}
Output:
10 20
//////////////////////////////////////////////////////////////////////////////
What is a structure pointer?
Like primitive types, we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.
members are accessed using arrow ( -> ) operator.
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf("%d %d", p2->x, p2->y);
return 0;
}
|
Output:
1 2
Structure Member Alignment, Padding
and Data Packing
and Data Packing
#include <stdio.h>
// Alignment requirements
// (typical 32 bit machine)
// char 1 byte
// short int 2 bytes
// int 4 bytes
// double 8 bytes
// structure A
typedef struct structa_tag
{
char c;
short int s;
} structa_t;
// structure B
typedef struct structb_tag
{
short int s;
char c;
int i;
} structb_t;
// structure C
typedef struct structc_tag
{
char c;
double d;
int s;
} structc_t;
// structure D
typedef struct structd_tag
{
double d;
int s;
char c;
} structd_t;
int main()
{
printf("sizeof(structa_t) = %d\n", sizeof(structa_t));
printf("sizeof(structb_t) = %d\n", sizeof(structb_t));
printf("sizeof(structc_t) = %d\n", sizeof(structc_t));
printf("sizeof(structd_t) = %d\n", sizeof(structd_t));
return 0;
}
Answers:
sizeof(structa_t) = 4
sizeof(structb_t) = 8
sizeof(structc_t) = 24
sizeof(structd_t) = 16
sizeof(structb_t) = 8
sizeof(structc_t) = 24
sizeof(structd_t) = 16
Union in C
#include <stdio.h>
// Declaration of union is same as structures
union test
{
int x, y;
};
int main()
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf ("After making x = 2:\n x = %d, y = %d\n\n",
t.x, t.y);
t.y = 10; // t.x is also updated to 10
printf ("After making Y = 'A':\n x = %d, y = %d\n\n",
t.x, t.y);
return 0;
}
Output:
After making x = 2:
x = 2, y = 2
After making Y = 'A':
x = 10, y = 10
x = 2, y = 2
After making Y = 'A':
x = 10, y = 10
////////////////////////////////////////////////////////////////////////////
How is the size of union decided by compiler?
Size of a union is taken according the size of largest member in union.
#include <stdio.h>
union test1
{
int x;
int y;
};
union test2
{
int x;
char y;
};
union test3
{
int arr[10];
char y;
};
int main()
{
printf ("sizeof(test1) = %d, sizeof(test2) = %d,"
"sizeof(test3) = %d", sizeof(test1),
sizeof(test2), sizeof(test3));
return 0;
}
|
Output
sizeof(test1) = 4, sizeof(test2) = 4,sizeof(test3) = 40
//////////////////////////////////////////////////////////////////////
Pointers to unions?
Like structures, we can have pointers to unions and can access members using arrow operator (->).
The following example demonstrates the same.
The following example demonstrates the same.
union test
{
int x;
char y;
};
int main()
{
union test p1;
p1.x = 65;
// p2 is a pointer to union p1
union test *p2 = &p1;
// Accessing union members using pointer
printf("%d %c", p2->x, p2->y);
return 0;
}
|
65 A
Struct Hack
And what about size of “name[0]”. In gcc, when we create an array of zero length, it is considered as
array of incomplete type that’s why gcc reports its size as “0” bytes. This technique is known as
“Stuct Hack”.
array of incomplete type that’s why gcc reports its size as “0” bytes. This technique is known as
“Stuct Hack”.
struct employee
{
int emp_id;
int name_len;
char name[0];
};
4 + 4 + 0 = 8 bytes.
“Struct Hack” technique is used to create variable length member in a structure
struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128);
is equivalent to
struct employee
{
int emp_id;
int name_len;
char name[128]; /* character array of size 128 */
};
Note: since name is character array, in malloc instead of “sizeof(char) * 128”, we can use “128”
directly. sizeof is used to avoid confusion.
directly. sizeof is used to avoid confusion.
Now we can use “name” same as pointer. e.g.
e->emp_id = 100;
e->name_len = strlen("Geeks For Geeks");
strncpy(e->name, "Geeks For Geeks", e->name_len);
e->name_len = strlen("Geeks For Geeks");
strncpy(e->name, "Geeks For Geeks", e->name_len);
/////////////////////////////////////////////
Program 1
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2+
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return 0;
}
|
Program 2
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p1
if (p1 == p2) // compiler error: cannot do equality check for
// whole structures
{
printf("p1 and p2 are same ");
}
getchar();
return 0;
}
////////////////////
Bit Fields in C
#include <stdio.h>
// A simple representation of date
struct date
{
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 12 bytes
Date is 31/12/2014
Date is 31/12/2014
///////////////////////////////////////////////////////////////////////////////////////
struct student
{
int stud_id;
int name_len;
int struct_size;
char stud_name[];
};
The size of structure is = 4 + 4 + 4 + 0 = 12
In the above code snippet, the size i.e length of array “stud_name” isn’t fixed and is an FAM.
The memory allocation using flexible array members(as per C99 standards) for the above
example can be done as:
example can be done as:
struct student *s = malloc( sizeof(*s) + sizeof(char [strlen(stud_name)]) );
Similarities between Structure and Union
- Both are user-defined data types used to store data of different types as a single unit.
- Their members can be objects of any type, including other structures and unions or arrays.
A member can also consist of a bit field. - Both structures and unions support only assignment = and sizeof operators. The two structures
or unions in the assignment
must have the same members and member types. - A structure or a union can be passed by value to functions and returned by value by functions.
The argument must have the same
type as the function parameter. A structure or union is passed by value just like a scalar
variable as a corresponding parameter. - ‘.’ operator is used for accessing members.
Difference
Difference between C structures and C++
structures
1Direct Initialization: We cannot directly initialize structure data members in C but we can
do it in C++.
do it in C++.
For c
#include<stdio.h>
struct Record
{
int x = 7;
};
// Driver Program
int main()
{
struct Record s;
printf("%d", s.x);
return 0;
}
/* Output : Compiler Error
6:8: error: expected ':', ',', ';', '}' or
'__attribute__' before '=' token
int x = 7;
^
In function 'main': */
For c++
// CPP program to initialize data member in c++
#include<iostream>
using namespace std;
struct Record
{
int x = 7;
};
// Driver Program
int main()
{
Record s;
cout << s.x << endl;
return 0;
}
// Output
// 7
2.Using struct keyword: In C, we need to use struct to declare a struct variable. In C++, struct is
not necessary. For example, let there be a structure for Record. In C, we must use “struct Record”
for Record variables. In C++, we need not use struct and using ‘Record‘ only would work
not necessary. For example, let there be a structure for Record. In C, we must use “struct Record”
for Record variables. In C++, we need not use struct and using ‘Record‘ only would work
3.Static Members: C structures cannot have static members but is allowed in C++.
struct Record
{
static int x;
};
// Driver program
int main()
{
return 0;
}
/* 6:5: error: expected specifier-qualifier-list
before 'static'
static int x;
^*/
// C++ program with structure static member
struct Record
{
static int x;
};
// Driver program
int main()
{
return 0;
}
This will generate an error in C but no error in C++.
///////////////////////////////////////////////
sizeof operator: This operator will generate 0 for an empty structure in C whereas 1 for an empty
structure in C++. // C program to illustrate empty structure #include<stdio.h> //empty structure struct Record { }; //Driver program int main() { struct Record s; printf("%d\n",sizeof(s)); return 0; } Output in C: 0 Output in C++: 1 Structure vs class in C++
In C++, a structure is same as class except the following differences:
1) Members of a class are private by default and members of struct are public by default.
For example program 1 fails in compilation and program 2 works fine.
2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is
public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}
Anonymous Union and Structure in C
#include<stdio.h>
struct Scope
{
// Anonymous union
union
{
char alpha;
int num;
};
};
int main()
{
struct Scope x;
x.num = 65;
// Note that members of union are accessed directly
printf("x.alpha = %c, x.num = %d", x.alpha, x.num);
return 0;
}
Output:
x.alpha = A, x.num = 65
Output:
x.alpha = B, x.num = 65
What about C++?
Anonymous Unions and Structures are NOT part of C++
Compound Literals in C
Consider below program in C.
Output:
2 4 6
..............................................................................................................................................Memory Layout of C Programs
A typical memory representation of C program consists of following sections.
1. Text segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap
1. Text Segment:
A text segment , also known as a code segment or simply as text, is one of the sections of
a program in an object file or in memory, which contains executable instructions.
2. Initialized Data Segment:
Initialized data segment, usually called simply the Data Segment. A data segment is a portion
of virtual address space of a program, which contains the global variables and static variables that are initialized by the programme.
3. Uninitialized Data Segment:
Uninitialized data segment, often called the “bss” segment, named after an ancient assembler
operator that stood for “block started by symbol.” Data in this segment is initialized by the kerne l to arithmetic 0 before the program starts executing.
4. Stack:
The stack area traditionally adjoined the heap area and grew the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and virtual memory techniques they may be placed almost anywhere, but they still typically grow opposite directions.)
5. Heap:
Heap is the segment where dynamic memory allocation usually takes place.
How to deallocate memory without using free() in C?
//Code with memory leak
#include <stdio.h>
int main(void)
{
return 0;
}
[narendra@CentOS]$ gcc memory-layout.c -o memory-layout
[narendra@CentOS]$ size memory-layout text data bss dec hex filename 960 248 8 1216 4c0 memory-layout
Let us check with simple example.
Check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is
highlighed in red colour.
[narendra@ubuntu]$ valgrind –leak-check=full ./free
==1238== LEAK SUMMARY: ==1238== definitely lost: 10 bytes in 1 blocks. ==1238== possibly lost: 0 bytes in 0 blocks. ==1238== still reachable: 0 bytes in 0 blocks. ==1238== suppressed: 0 bytes in 0 blocks. [narendra@ubuntu]$
Let us modify the above code.
Check the valgrind’s output. It shows no memory leaks are possible, highlighted in red color.
calloc() versus malloc()
/ C program to demonstrate the use of calloc()
// and malloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
// malloc() allocate the memory for 5 integers
// containing garbage values
arr = (int *)malloc(5 * sizeof(int)); // 5*4bytes = 5 bytes
// Deallocates memory previously allocated by malloc() function
free( arr );
// calloc() allocate the memory for 5 integers and
// set 0 to all of them
arr = (int *)calloc(5, sizeof(int));
// Deallocates memory previously allocated by calloc() function
free(arr);
return(0);
}
We can achieve same functionality as calloc() by using malloc() followed by memset(),
Note: It would be better to use malloc over calloc, unless we want the zero-initialization because
malloc is faster than calloc. So if we just want to copy some stuff or do something that doesn’t require filling of the blocks with zeros, then malloc would be a better choice.
Malloc vs calloc
Use of realloc()
Program 1:
Output:
Undefined Behavior
Program 2:
Output:
10 20 30
What is Memory Leak? How can we avoid?
Memory leak occurs when programmers create a memory in
heap and forget to delete it.
/* Function with memory leak */
#include <stdlib.h>
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
return; /* Return without freeing ptr*/
}
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
/* Function without memory leak */
#include <stdlib.h>;
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
free(ptr);
return;
}
fork() vs exec()
The fork system call creates a new process. The new process created by fork() is copy of the
current process except the returned value. The exex system call replaces the current process with a new program.Type of errors ///srlls
1.Syntax errors: Errors that occur when you violate the rules.
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Error:
error: expected ';' before '}' token
2.Run-time Errors : Errors which occur during program execution(run-time) after
successful compilation are called run-time errors.
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Error:
warning: division by zero [-Wdiv-by-zero]
div = n/0;
3.Linker Errors: These error occurs when after compilation we link the different object
files with main’s object using Ctrl+F9 key(RUN).
// C program to illustrate
// linker error
#include<stdio.h>
void Main() // Here Main() should be main()
{
int a = 10;
printf("%d", a);
}
4.Logical Errors :
// C program to illustrate
// logical error
int main()
{
int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{
printf("loop ");
continue;
}
getchar();
return 0;
}
5.Semantic errors :
void main()
{
int a, b, c;
a + b = c; //semantic error
}
C and c++
1) In C, functions can be defined using a syntax that optionally specifies argument types after the
list of arguments:
Output:
8 9
Error in C++ :- a and b was not declared in this scope
2) In C and in pre-standard versions of C++, the type specifier defaults to int.
Output:
7
Error in C++ :- a does not name a type
3) In C, a global data object may be declared several times without using the extern specifier.
As long as at most one such declaration provides an initializer, the object is considered defined only once.
Error in C++ :- Redefinition of int a
4.In C, a void* may be used as the right-hand operand of an assignment to or initialization of a
variable of any pointer type.
Error in C++ :- Invalid conversion of void* to int*
5) In C, an array can be initialized by an initializer that has more elements than the array requires.
Output:
Geeks
Error in C++ :- Initializer-string for array of chars is too long
6) In C, a function declared without specifying any argument types can take any number of
arguments of any type at all. Click here to know more about this.
Error in C++ :- Too many arguments to function 'void fun()'
Program 3
Output:
error: invalid conversion from 'void*' to 'char*
Explanation: Assigning any pointer type to a void pointer without using a cast is allowed in
C or C++. But we can not assign a void pointer to a non-void pointer without using a cast to non-void pointer type in C++. Hence statement one should be —
ptr2 = (char*)ptr1; // valid in C++
Program 4
Output:
error: uninitialized const 'size'
Explanation: At first glance its obvious to think that output will be some garbage value, but it is
not the case. Unlike C in C++ any variable declared as constant needs to be initialized at the time of declaration. Hence the given code will not compile and throw the error. It should be noted that the same code will get compiled in ANSI C and will produce output as 0.
1) The case labels of a switch statement can occur inside if-else statements.
Output :
GeeksforGeeks
3) We can use ‘<:, :>’ in place of ‘[,]’ and ‘<%, %>’ in place of ‘{,}’
Output :
1
4) Using #include in strange places.
Let “a.txt” contains (“GeeksforGeeks”);
Output :
GeeksforGeeks
5) We can ignore input in scanf() by using an ‘*’ after ‘%’ in format specifiers
#include<stdio.h>
int main()
{
int a;
// Let we input 10 20, we get output as 20
// (First input is ignored)
// If we remove * from below line, we get 10.
scanf("%*d%d", &a);
printf( "%d ", a);
return 0;
}
L-value: “l-value” refers to memory location which identifies an object. l-value may
appear as either left hand or right hand side of an assignment operator(=). l-value often represents as identifier.
R-value: r-value” refers to data value that is stored at some address in memory.
A r-value is an expression that can’t have a value assigned to it which means r-value can appear on right but not on left hand side of an assignment operator(=).
.............................................................
puzzle in c
1.C Program to print numbers from
1 to N without using semicolon?
Method 1 (Recursive)
// A recursive C program to print all numbers from 1
// to N without semicoolon
#include<stdio.h>
#define N 10
int main(int num)
{
if (num <= N && printf("%d ", num) && main(num + 1))
{
}
}
Method 2 iterative
#include<stdio.h>
#define N 10
int main(int num, char *argv[])
{
while (num <= N && printf("%d ", num) && num++)
{
}
}
2.To find sum of two numbers without
using any operator
int add(int x, int y)
{
return printf("%*c%*c", x, ' ', y, ' ');
}
int main()
{
printf("Sum = %d", add(3, 4));
return 0;
}
3.Condition To Print “HelloWord”
Method 1:
#include<stdio.h>
int main()
{
if(!printf("Hello"))
printf("Hello");
else
printf("World");
getchar();
}
#include<stdio.h>
#include<unistd.h>
int main()
{
if(fork())
printf("Hello");
else
printf("World");
getchar();
}
4.Program to compute Log n
// C program to find log(n) using Recursion
#include <stdio.h>
unsigned int Log2n(unsigned int n)
{
return (n > 1) ? 1 + Log2n(n / 2) : 0;
}
int main()
{
unsigned int n = 32;
printf("%u", Log2n(n));
getchar();
return 0;
}
5How will you print numbers from 1 to
100 without using loop?
#include <stdio.h>
// Prints numbers from 1 to n
void printNos(unsigned int n)
{
if(n > 0)
{
printNos(n - 1);
printf("%d ", n);
}
return;
}
// Driver code
int main()
{
printNos(100);
getchar();
return 0;
}
6Print “Even” or “Odd” without using
conditional statement
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char arr[2][5] = {"Even", "Odd"};
int no;
cout << "Enter a number: ";
cin >> no;
cout << arr[no%2];
getch();
return 0;
}
7.Write a C program to print “Geeks for
Geeks” without using a semicolon
#include<stdio.h>
int main()
{
if (printf("Geeks for Geeks") )
{ }
}
8,Write a one line C function to round
floating point numbers
# include<stdio.h>
int roundNo(float num)
{
return num < 0 ? num - 0.5 : num + 0.5;
}
int main()
{
printf("%d", roundNo(-1.777));
getchar();
return 0;
}
9.How to write a running C code without
main()?
#include<stdio.h>
#define fun m##a##i##n
int fun()
{
printf("Geeksforgeeks");
return 0;
}
10.C program to print characters without
using format specifiers
#include <stdio.h>
int main()
{
printf("\x47 \n");
printf("\x45 \n");
printf("\x45 \n");
printf("\x4b \n");
printf("\x53");
return 0;
}
11.Execute both if and else statements in
C/C++ simultaneously
int main()
{
if (1) //Replace 1 with 0 and see the magic
{
label_1: printf("Hello ");
// Jump to the else statement after
// executing the above statement
goto label_2;
}
else
{
// Jump to 'if block statement' if
// the Boolean condition becomes false
goto label_1;
label_2: printf("Geeks");
}
return 0;
}
12.Print “Hello World” in C/C++ without using
any header file
int printf(const char *format, ...);
int main()
{
printf( "Hello World" );
return 0;
}
13.Write a C program that does not terminate
when Ctrl+C is pressed
void sigintHandler(int sig_num)
{
/* Reset handler to catch SIGINT next time.
signal(SIGINT, sigintHandler);
printf("\n Cannot be terminated using Ctrl+C \n");
fflush(stdout);
}
int main ()
{
/* Set the SIGINT (Ctrl-C) signal handler to sigintHandler
signal(SIGINT, sigintHandler);
/* Infinite loop */
while(1)
{
}
return 0;
}
14.C program to print a string without any
quote (singe or double) in the program
#include <stdio.h>
#define get(x) #x
int main()
{
printf(get(vignesh));
return 0;
}
//vignesh
calloc() allocates the memory and also initializes the allocates memory block to zero. If we try to
access the content of these blocks then we’ll get 0.
Number of arguments: Unlike malloc(), calloc() takes two arguments:
1) Number of blocks to be allocated.
2) Size of each block.
Return Value: After successfull allocation in malloc() and calloc(), a pointer to the block of
memory is returned otherwise NULL value is returned which indicates the failure of allocation. |
c and ds nitt
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main()
{
int n;
scanf("%d",&n);
int *arr = malloc(sizeof(int) * n);
for(int arr_i = 0; arr_i < n; arr_i++){
scanf("%d",&arr[arr_i]);
}
for(int j= n-1;j>=0;j--)
{
printf("%d ",arr[j]);
}
return 0;
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 200 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
}
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 200 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
}
When the above code is compiled and executed, it produces the following result.
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Description: Zara ali a DPS student in class 10th
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcpy( description, "Zara ali a DPS student.");
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* release memory using free() function */
free(description);
}
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcpy( description, "Zara ali a DPS student.");
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* release memory using free() function */
free(description);
}
When the above code is compiled and executed, it produces the following result.
Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th
Description: Zara ali a DPS student.She is in class 10th
C++ vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for(i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
#include <vector>
using namespace std;
int main() {
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for(i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
////////////////////
to run c++ program
g++ filename.c
./filename
////////////////////////////
Comments
Post a Comment