DynMemory Programs
DynMemory Programs
DynMemory Programs
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
// Program on realloc
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);
// Input 'n' numbers and store them dynamically in the allocated memory
for (i = 0; i < n; ++i) {
printf(" Number %d: ", i + 1);
scanf("%f", element + i);
}
// Find the largest element among the 'n' elements
for (i = 1; i < n; ++i) {
if (*element < *(element + i)) {
*element = *(element + i); // Store the largest element in the first
memory location
}
}
printf(" The Largest element is : %.2f \n\n", *element); // Display the
largest element found
return 0;
}
Write a program in C to print all permutations of a given string
using pointers.
#include <stdio.h>
#include <string.h>
// Main function
int main()
{
char str[] = "abcd"; // The input string
printf("\n\n Pointer : Generate permutations of a given string :\n");
printf("--------------------------------------------------------\n");
int n = strlen(str); // Get the length of the string
printf(" The permutations of the string are : \n");
charPermu(str, 0, n - 1); // Call function to generate permutations
printf("\n\n");
return 0;
}
// Function to generate permutations of a string
void charPermu(char *cht, int stno, int endno)
{
int i;
if (stno == endno)
printf("%s ", cht); // Print the generated permutation when stno equals
endno
else
{
for (i = stno; i <= endno; i++)
{
changePosition((cht + stno), (cht + i)); // Swap characters at
positions stno and i
charPermu(cht, stno + 1, endno); // Recursively generate
permutations for the rest of the string
changePosition((cht + stno), (cht + i)); // Restore the original string
by swapping back
}
}
}