我似乎无法为指针分配一个数组,然后更改数组的内容

I cant seem to assign a pointer an array and then change the contents of the array

本文关键字:数组 然后 一个 指针 分配      更新时间:2023-10-16

我不知道如何让函数返回数组,所以我决定尝试将一个空数组(大小正确(传递到我的函数中,而不是将地址重新分配给相同大小的不同数组。这到底是一种做事方式吗???有人可以告诉我该怎么做吗?如果这是错误的,你能告诉我如何做到这一点吗?

这是我的代码:

#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray,int s, int f){
int *ptrarray = &earray;
int prenum_size = std::abs(s) + f - 1;
int pre_num[prenum_size];
for(int x=s;x<f;x++){
pre_num[x+std::abs(s)] = x;
}
*ptrarray = pre_num;
}

int Main(){
int first = -10;
int second = 15;
int temp[abs(first) + abs(second)];
ArrayFiller(temp, first, second);

int n = sizeof(temp)/sizeof(temp[0]);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
return 0;
}

我想你正在寻找这样的东西:

#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray[],int s, int f){
for(int x=s;x<f;x++){
earray[x+(std::abs(s))] = x;
}
}
int main(){
int first = -10;
int second = 15;
int n = abs(first)+abs(second);
int* temp = new int[n];
ArrayFiller(temp, first, second);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
delete [] temp;
return 0;
}
相关文章: