c++ - 未初始化的局部变量并帮助更正

标签 c++ sorting pointers dynamic

我正在类里面学习指针和 new 运算符。

在我的 readArray 函数中,我要读取一个大小。使用大小动态创建一个整数数组。然后将数组赋给一个指针,填充它,返回大小和数组。

我相信我已经纠正并修复了那部分,但是当我尝试对数组进行排序时,我收到错误消息 “未初始化的局部变量 temp 已使用。”

问题是我在尝试初始化它时遇到了那个错误。 任何帮助表示感谢谢谢。看到我的错误对我很有帮助。

#include <iostream>
using namespace std;

int* readArray(int&);
void sortArray(int *, const int * );

int main ()
{
    int size = 0;
    int *arrPTR = readArray(size);
    const int *sizePTR = &size;
    sortArray(arrPTR, sizePTR);

    cout<<arrPTR[1]<<arrPTR[2]<<arrPTR[3]<<arrPTR[4];

        system("pause");
        return 0;
}


int* readArray(int &size)
{
    cout<<"Enter a number for size of array.\n";
    cin>>size;
    int *arrPTR = new int[size];

    for(int count = 0; count < (size-1); count++)
    {   
         cout<<"Enter positive numbers to completely fill the array.\n";
         cin>>*(arrPTR+count);
    }

    return arrPTR;
}

void sortArray(int *arrPTR, const int *sizePTR)
{
    int *temp;
    bool *swap;

    do
    {
        swap = false;
        for(int count = 0; count < (*sizePTR - 1); count++)
        {
            if(arrPTR[count] > arrPTR[count+1])
            {
                *temp = arrPTR[count];
                arrPTR[count] = arrPTR[count+1];
                arrPTR[count+1] = *temp;
                *swap = true;
            }
        }
    }while (swap);
 }

最佳答案

你使 temp 成为一个 int 指针(未初始化),然后将它指向的东西(任何东西/什么东西)设置为 arrPTR[ccount]。由于您仅使用 temp 进行交换,因此它应该与被交换的类型相同,在本例中为:int。

如果它绝对必须是一个指针(没有没有好的理由,它很慢,令人困惑,增加了错误的可能性,并增加了内存泄漏的可能性) :

int *temp = new int; //make an int for the pointer to point at
bool *swap = new bool; //make an bool for the pointer to point at
do
{
    //your code
}while (swap);
delete temp;
delete swap;

关于c++ - 未初始化的局部变量并帮助更正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314788/

相关文章:

c++ - 为什么我的变量被覆盖了?

c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?

c++ - 为什么 lambda 函数默认删除推导的返回类型引用?

php - 有没有更好的方法来进行排序选项?

algorithm - 这3个类轮是什么排序算法?

vb.net - 在 VB 中对列表框项目进行数字排序

c++ - 使用多态时如何避免向下转换?

c++ - 用C++写一个简单的类

c++ - 使用 strdup() 后将 char* 转换为 int

c - 指针作为调用 scanf 的函数的参数