为什么数组在一个文件中打印,但在发送到另一个文件时却缺少数字

Why is the array printing in one file, but missing numbers when sent to another

本文关键字:文件 另一个 数字 打印 数组 为什么 一个      更新时间:2023-10-16

main看起来是这样的,它编译得很好,但当它调用以显示ptr所指向的数组时,出现了问题

#include "tools.h"
#include <iostream>
using namespace std;

int main()
{
short int Arr1[] = { 5, 10 , 20 , 33, 444};
short int Arr2[] = {8, 1, 22, 333, 4, 555, 6, 7777};
short int* nptr ;
short int* ar1 = Arr1;
short int* ar2 = Arr2;
Display(ar1);
Display(ar2);
nptr = Concat(ar1,ar2);
Display(nptr);
}

这是我从中获取函数的文件,前两个数组的显示似乎很好,当打印数组时,仍在此文件中

#include <iostream>
using namespace std;
void Display (short int* a)
{
short int ArraySize = *a; 
short int num = *a;
for(short int i = 0; i < ArraySize; ++i)
{
num  = *(a+i);
cout << num;
cout << "  ";
}
cout << endl;
}


short int* Concat(short int* a1, short int* a2)
{       
short int ArraySize = *a1 + *a2 + 1;
cout << ArraySize << endl;
short int Arr[ArraySize];
short int num1 = *a1;
short int num2 = *a2;   
short int* ptr;
ptr = &Arr[0];
Arr[0] = ArraySize;
for(short int i = 0; i < *a1; i++)
{
num1 = *(a1+i);
Arr[i+1] = num1;
}
for (short int i = 0; i < *a2; i++)
{      
num2 = *(a2+i);
Arr[i+*a1+1] = num2;
}
Display(ptr);
return ptr;
} 

然后输出看起来像这个

5  10  20  33  444      // this line is fine
8  1  22  333  4  555  6  7777   // this line is fine
14 // fine
14  5  10  20  33  444  8  1  22  333  4  555  6  7777 // the way the array should be printed 
14  5  10  20  3448  64  0  0  4736  96  0  0  2096  64 // the way it is printing and I need to fix

如果有人输入了为什么要这样做,或者我可以做些什么来修复它。我需要从主程序打印数组,而不是从文件打印。

我还想提一下,我对这种语言的指针还相当陌生。

好吧,我想你有几点不清楚。

首先,你在这里不处理任何文件。这些是在堆栈上分配的数组。它们是特定的大小,不能更改。

抱歉,如果我似乎在贬低你,那不是我的本意,但从你在这里所做的事情来看,你似乎不理解堆栈的概念。

程序使用堆栈来跟踪它的位置,并存储局部变量。当您调用一个函数时,它会将返回地址"推送"到堆栈,并在堆栈上为该函数中的局部变量分配空间。当您从一个函数返回时,它会"弹出"堆栈并返回到上一个地址。当这种情况发生时,函数中的局部变量将不再有效。

在您的代码中,您在Concat()中声明了一个局部变量。当您从Concat()返回时,堆栈将弹出,并且您返回到该局部变量的指针不再有效。

要执行您要执行的操作,您需要在main()中声明另一个数组,该数组足够大,可以容纳您需要的内容。您将把指向该新数组的指针作为第三个参数传递给Concat()。

不要让消极情绪让你失望。没有人天生就是这方面的专家。

相关文章: