Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 此数组中的某些值没有特殊原因而变为零(0)_C++_Arrays_Function_Zero - Fatal编程技术网

C++ 此数组中的某些值没有特殊原因而变为零(0)

C++ 此数组中的某些值没有特殊原因而变为零(0),c++,arrays,function,zero,C++,Arrays,Function,Zero,我获取一个数组的输入,然后运行一个完全无关的函数。不知何故,数组的值在这一点之后是不同的。 据我所知,前几个值变为零(0) 以下是主要功能的开始部分: int main() { int i, j, k, n; Nod* root=NULL; //Nod class user defined elsewhere cin>>n; int A[n]; for(i=0; i<n; i++) { cin>

我获取一个数组的输入,然后运行一个完全无关的函数。不知何故,数组的值在这一点之后是不同的。 据我所知,前几个值变为零(0)

以下是主要功能的开始部分:

int main()
{
    int i, j, k, n;
    Nod* root=NULL;    //Nod class user defined elsewhere
    cin>>n;
    int A[n];
    for(i=0; i<n; i++)
      {
          cin>>A[i];
          cout<<A[i]<<"\t";//TESTER
      }
    cout<<endl<<endl;
    Nod no[n];
    for(i=0; i<n; i++)
       no[i].nowhere(n);
    for(i=0; i<n; i++)
       cout<<A[i]<<"\t";//TESTER
    cout<<endl<<endl;

    ...//rest of main()
    ...
}
class Nod
{
    public: Nod* parent;
    Nod* child[];

    void nowhere(int n)
        {
            parent=NULL;
            for(int i=0; i<n; i++)
                child[i]=NULL;
        }
};
输出:


就我所见,
nowhere()
函数不应该影响数组
A[
]。那么,这些值是如何变化的呢?

函数
无处
通过写入子[]数组的末尾,导致未定义的行为。该数组在您的场景中没有元素,因此访问任何索引都会导致未定义的行为

由于您正在数组中分配
Nod
s,因此应将
child[]
更改为
std::vector child
,并根据需要动态将其初始化为适当的大小:

std::vector<Nod*> child;

void nowhere(int n) {
    parent = NULL;
    child = std::vector<Nod*>(n, NULL);
}
std::向量子;
无处无效(整数n){
parent=NULL;
child=std::vector(n,NULL);
}

<强>注释:< /强>考虑重构代码以不使用“原始”指针或指针的向量。切换到智能指针,或尽可能使用对象。

您的问题:

由于
无处(int n)
覆盖
A[n]
的某些内容而导致未定义的行为,因此
int A[n]
的前两个单元格中都会出现零。以下循环执行此操作:

for(int i=0; i<n; i++)
   child[i]=NULL;
然后,像这样重写
nowhere(int n)

std::vector<Nod*> child;
void nowhere(int n)
{
    parent=NULL;
    child.resize(n);
    for(int i=0; i<n; i++)
        child[i]=NULL;
}
void nowhere(int n)
{
parent=NULL;
调整大小(n);

对于(int i=0;Iy需要a)。您不能通过猜测和查看交织上的代码片段。<代码> NOD*CHOD[];< /Code >不做您想象的那样。它不是合法的C++。也不是<代码> CIN > n;int a [n];< /Code >。如果您使用g++或CLAN,这些标志是强制性的:<代码> -STD= C++ 17 - Word-Word-Poognic < /Code >。(如果您的gcc太旧,您可能需要使用一些较低的数字;请参阅您发布的文档)。此外,使用VLA也是一个坏主意
std::vector<Nod*> child;
void nowhere(int n)
{
    parent=NULL;
    child.resize(n);
    for(int i=0; i<n; i++)
        child[i]=NULL;
}