phatboislym

Untitled

Dec 27th, 2022
847
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Function to print the elements of an array
  5. void print_array(int* array, int size) {
  6.   // Traverse the array and print the elements
  7.   for (int i = 0; i < size; i++) {
  8.     printf("a[%d] = %d\n", i, array[i]);
  9.   }
  10. }
  11.  
  12. // Function to insert an element at the beginning of an array
  13. int* insert_array(int* array, int data, int size) {
  14.   // Allocate memory for the new array
  15.   int* b = malloc(sizeof(int) * (size + 1));
  16.   // Check if the memory allocation was successful
  17.   if (b == NULL) {
  18.     // Return NULL if the memory allocation failed
  19.     return NULL;
  20.   }
  21.  
  22.   // Insert the data element at the beginning of the array
  23.   b[0] = data;
  24.   // Copy the elements of the original array into the new array
  25.   for (int j = 1; j <= size; j++) {
  26.     b[j] = array[j - 1];
  27.   }
  28.  
  29.   // Return a pointer to the new array
  30.   return b;
  31. }
  32.  
  33. int main(void) {
  34.   int a[] = {2, 6, 7, 9, 3, 5};
  35.   // Getting the length of the array
  36.   int size = (sizeof(a) / sizeof(a[0]));
  37.   int new = 10;
  38.   int index = 3;
  39.  
  40.   print_array(a, size);
  41.   int* bz = insert_array(a, new, size);
  42.   // Check if insert_array returned a valid pointer
  43.   if (bz == NULL) {
  44.     printf("Failed to insert element into array\n");
  45.     return 1;
  46.   }
  47.   print_array(bz, (size + 1));
  48.  
  49.   // Release the memory occupied by the new array
  50.   free(bz);
  51.  
  52.   return 0;
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment