[英]How to pass the pointer of main Dlg from a thread to a function inside in MFC
[英]How to pass a pointer to an array from main to a function?
基本上,我試圖根據輸入設置數組的大小(將要求用戶提供numArraySize)。 我在main中創建了一個數組指針,並希望將此指針傳遞給函數。
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int *numbers = new int[numArraySize];
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
return 0;
}
編輯:
好吧,我修復了錯誤。 我更改了:“ int numArraySize = 1;” 以及“ int *數字= new int [numArraySize];”的位置
問題是我還是必須初始化numArraySize。 這顯然會導致錯誤。 第二個問題是我必須在主函數中初始化“ int *數字”之前輸入numArraySize。
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize=1;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
int *numbers = new int[numArraySize];
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
system("pause");
return 0;
}
謝謝您的幫助:)
當您為行中的數組分配內存時
int *numbers = new int[numArraySize]
,您仍未在變量numArraySize中收到所需的數組大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.