Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- // Function to print the elements of an array
- void print_array(int* array, int size) {
- // Traverse the array and print the elements
- for (int i = 0; i < size; i++) {
- printf("a[%d] = %d\n", i, array[i]);
- }
- }
- // Function to insert an element at the beginning of an array
- int* insert_array(int* array, int data, int size) {
- // Allocate memory for the new array
- int* b = malloc(sizeof(int) * (size + 1));
- // Check if the memory allocation was successful
- if (b == NULL) {
- // Return NULL if the memory allocation failed
- return NULL;
- }
- // Insert the data element at the beginning of the array
- b[0] = data;
- // Copy the elements of the original array into the new array
- for (int j = 1; j <= size; j++) {
- b[j] = array[j - 1];
- }
- // Return a pointer to the new array
- return b;
- }
- int main(void) {
- int a[] = {2, 6, 7, 9, 3, 5};
- // Getting the length of the array
- int size = (sizeof(a) / sizeof(a[0]));
- int new = 10;
- int index = 3;
- print_array(a, size);
- int* bz = insert_array(a, new, size);
- // Check if insert_array returned a valid pointer
- if (bz == NULL) {
- printf("Failed to insert element into array\n");
- return 1;
- }
- print_array(bz, (size + 1));
- // Release the memory occupied by the new array
- free(bz);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment