 Carlos Arronte Bello -4 years ago 78
C++ Question

# Array size defined by user

I have the following code:

``````#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

#define N 2  /* # of thread */

int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};  /* target array */

/* structure for array index
* used to keep low/high end of sub arrays
*/
typedef struct Arr {
int low;
int high;
} ArrayIndex;

void merge(int low, int high)
{
int mid = (low+high)/2;
int left = low;
int right = mid+1;

int b[high-low+1];
int i, cur = 0;

while(left <= mid && right <= high) {
if (a[left] > a[right])
b[cur++] = a[right++];
else
b[cur++] = a[right++];
}

while(left <= mid) b[cur++] = a[left++];
while(right <= high) b[cur++] = a[left++];
for (i = 0; i < (high-low+1) ; i++) a[low+i] = b[i];
}

void * mergesort(void *a)
{
ArrayIndex *pa = (ArrayIndex *)a;
int mid = (pa->low + pa->high)/2;

ArrayIndex aIndex[N];

aIndex.low = pa->low;
aIndex.high = mid;

aIndex.low = mid+1;
aIndex.high = pa->high;

if (pa->low >= pa->high) return 0;

int i;

merge(pa->low, pa->high);

return 0;
}

int main()
{
ArrayIndex ai;
ai.low = 0;
ai.high = sizeof(a)/sizeof(a)-1;

int i;
for (i = 0; i < 10; i++) printf ("%d ", a[i]);
cout << endl;

return 0;
}
``````

The code is working. But I need some help with this. I need to know how to ask the user the size of the array
`a[]`
and create the array randomly. I really appreciate the help. Thanks in advanced and sorry for bad English. Jahid

You use vector for this purpose. An example:

``````#include <vector>
...

std::vector<int> myarr;  //Note: No size is specified.
myarr.push_back(10);     //inserting an element at end of myarr
myarr.push_back(11);     //inserting another
std::cout<<myarr.size(); //number of element
//You can keep doing these things.
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download