小编Sha*_*edi的帖子

如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会改变?

using namespace std;
#include<iostream>
int passarr(int b[],int s)
{
   //Some Modification in the array b
    b[0]=0;
    b[s-1]=0;

    //Printing the array b
    for(int i=0;i<s;i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;
}
int main()
{
    int arr[100];
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }

    //Function call and passing array a to the function`
    passarr(arr,n);

    //Printing the array arr
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我已经将数组传递arr给了函数passarr(),它执行了一些修改.问题是修改也反映在原始数组上.有没有办法将数组传递给函数,以便在执行函数中的任何操作时不会更改原始数组?

c++ arrays function

2
推荐指数
1
解决办法
84
查看次数

使用 getline 函数获取分段错误?

我的代码出现分段错误。我使用了调试器并将错误定位到第 14 行。它没有将输入存储在第 13 行,这就是第 14 行抛出越界错误的原因。谁能告诉我为什么第 13 行不起作用?

using namespace std;
#include<iostream>
#include<cstring>
#include<deque>
int main()
{
    int n;
    cout<<"How many messages to read: ";
    cin>>n;
    string s;
    for(int i=1;i<=n;i++)
    {
        getline(cin,s);       //<-----LINE13
        auto it=s.begin();    //<-----LINE14
        deque<char> kingdom;
        while(s[0]!=',')
        {
            kingdom.push_back(s[0]);
            s.erase(it);
        }
        s.erase(it);
        s.erase(it);
        s.erase(it);
        while(kingdom.size()!=0)
        {
            it=s.begin();
            for(int j=0;j<s.length();j++,it++)
            {
                if(kingdom.at(0)==s.at(j))
                {
                    kingdom.pop_front();
                    s.erase(it);
                    break;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

c++ string

1
推荐指数
1
解决办法
193
查看次数

标签 统计

c++ ×2

arrays ×1

function ×1

string ×1