Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How to dynamically allocate an array in C? My merge sort program fails at 1 million integer input. I understand I need to use malloc,

How to dynamically allocate an array in C?

My merge sort program fails at 1 million integer input. I understand I need to use malloc, but I have no idea how to implement it. All of the online how to guides seem to leave out what all the syntax parts are supposed to be. I would be very greatful if someone could take my code and show me how to dynamically allocate my array, so when I generate random numbers, and feed them into the array, I do not get a stack overflow.

PLEASE DO NOT JUST TYPE THE SYNTAX FOR MALLOC. I have looked that up many many times. Show me how to put it in my code, and I will rate immediately.

#include #include int count = 0; #define z 1000000 // THIS IS THE NUMBER OF INTEGERS I GENERATE. I HAVE BEEN MANUALLY TYPING IT IN BEFORE I FEED IT 1 MILLION RANDOM NUMBERS TO SORT

int arr[z]; //THIS IS WHERE I HAVE BEEN DECLARING MY ARRAY void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++) L[i] = arr[l + i]; count++;

for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; count++;

i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; count++; } else { arr[k] = R[j]; j++; count++; } k++; count++; }

while (i < n1) { arr[k] = L[i]; i++; k++; count++; }

while (j < n2) { arr[k] = R[j]; j++; k++; count++; } }

void mergeSort(int arr[], int l, int r) { if (l < r) {

int m = l+(r-l)/2;

mergeSort(arr, l, m); mergeSort(arr, m+1, r);

merge(arr, l, m, r); } }

void printArray(int A[], int size) { int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf(" "); }

int main(void) { int i; FILE *myFile; myFile = fopen("alg.txt","r");

int n = sizeof(arr)/sizeof(arr[0]); for(i=0; i < z; i++) { fscanf(myFile, "%d,", &arr[i]); }

mergeSort(arr, 0, n - 1);

printf(" Sorted array is "); printArray(arr, n); printf("count is %d ", count); return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle9i Database Administrator Implementation And Administration

Authors: Carol McCullough-Dieter

1st Edition

0619159006, 978-0619159009

More Books

Students also viewed these Databases questions