为什么数组在一个文件中打印,但在发送到另一个文件时却缺少数字
Why is the array printing in one file, but missing numbers when sent to another
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()。
不要让消极情绪让你失望。没有人天生就是这方面的专家。
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++ 如何打开带有另一个目录的输入文件?
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 程序在使用 system() 启动另一个可执行文件时停止
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 使用命名空间在另一个".cpp"文件中定义
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?