Program for malloc() function in C
#include
#include
#include
#include
int main()
{
char *mem_allocation;
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
Output
Dynamically allocated memory content: fresh2refresh
Program for calloc () function in C
#include
#include
#include
#include
int main()
{
char *mem_allocation;
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
Output
Dynamically allocated memory content : fresh2refresh
Program for realloc() and free() functions in C
#include
#include
#include
#include
int main()
{
char *mem_allocation;
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"space is extended upto " \
"100 characters");
}
printf("Resized memory : %s\n", mem_allocation );
free(mem_allocation);
}
Output
Dynamically allocated memory content: fresh2refresh
Resized memory: space is extended upto 100 characters
Resized memory: space is extended upto 100 characters
Program for perror() function in C
#include
#include
#include
int main()
{
FILE *fp;
char filename[40] = "test.txt";
fp = f open(filename, "r");
if(fp == NULL)
{
perror("File not found");
printf("errno : %d.\n", errno);
return 1;
}
printf("File is found and opened for reading");
fclose(fp);
return 0;
}
Output
errno: 22.
File not found: No such file or directory
File not found: No such file or directory
Program for rand () function in C
#include
#include
#include
int main ()
{
printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0;
}
Output
1st
random number : 83
2nd random number : 86
3rd random number: 16816927
2nd random number : 86
3rd random number: 16816927
Program for delay() function in C
#include
#include
int main ()
{
printf("Suspends the execution of the program " \"for particular time");
delay(5000);
return 0;
}
Output
Suspends the execution of the program for particular time
No comments:
Post a Comment