简体   繁体   English

c++ 程序如何返回我的数组或写入全局变量

[英]c++ program how can I return my array or write to a global variable

I am new with C++ and I have to write code, but somehow it is not working and I do not know what I can change.我是 C++ 的新手,我必须编写代码,但不知何故它不起作用,我不知道我可以改变什么。 I would like to give back the array Grad, but it says segmentation fault (core dumped).我想归还数组 Grad,但它说分段错误(核心转储)。 Could somebody help me with what I have to change?有人可以帮我解决我必须改变的事情吗? Or is it possible to have a global variable and write from the function directly to the global variable?或者是否可以有一个全局变量并从 function 直接写入全局变量? Thanks for your help.谢谢你的帮助。

Code:代码:


double* Gradient(const double x[], int n1) {
    double Grad [n1*4] = {0};
    // We calculate the overlap. If the overlap is zero, the gradient
    // is also zero. This should be probably improved in the future.
    //int n = sizeof(x)/32;
    for (int i = 0; i < n1*4; i++)
    {
        for (int j = 0; j < n1*4; i++)
        {
            if (i != j)
            {
                //cout << x[i]<< endl;
                double xmin = max(x[i*4], x[j*4]);
                double xmax = min(x[i*4+1], x[j*4+1]);
                //if (xmin > xmax) return Grad;
                double ymin = max(x[i*4+2], x[j*4+2]);
                double ymax = min(x[i*4+3], x[j*4+3]);
                //if (ymin > ymax) return Grad;

                double x_overlap = xmax-xmin;
                double y_overlap = ymax-ymin;

                // Gradient for xmin
                if (x[i*4] >= x[j*4] && x[i*4] != x[j*4+1] && x[i*4+1] 
!= x[j*4] && x[i*4+2] != x[j*4+3] && x[i*4+3] != x[j*4+2]) Grad[i*4] = 
Grad[i*4]-y_overlap;

                // Gradient for xmax
                if (x[i*4+1] < x[j*4+1]) Grad[i*4+1] = Grad[i*4+1] + 
y_overlap;

                // Gradient for ymin
                if (x[i*4+2] >= x[j*4+2] && x[i*4] != x[j*4+1] && 
x[i*4+1] != x[j*4] && x[i*4+2] != x[j*4+3] && x[i*4+3] != x[j*4+2]) 
Grad[i*4+2] = Grad[i*4+2]-x_overlap;

                // Gradient for ymax
                if (x[i*4+3] <= x[j*4+3]) Grad[i*4+3] = Grad[i*4+3] + 
x_overlap;

                // Gradient for xmax if rectangles are touching by the 
x-coordinate
                if (x[i*4+1] == x[j*4] && x[i*4+3] > x[j*4+2] && 
x[i*4+2] < x[j*4+3])
                {
                    Grad[i*4+1] = Grad[i*4+1] + y_overlap;
                }

                // Gradient for ymax if rectangles are touching by the 
y-coordinate
                if (x[i*4+3] == x[j*4+2] && x[i*4+1] > x[j*4] && x[i*4] 
< x[j*4+1])
                {
                    Grad[i*4+3] = Grad[i*4+3] + x_overlap;
                }
            }
        }
    }
    return Grad;
}


int main() {
    // Coordinates of the rectangles
    double x[] = {0,6,0,9,3,9,4,11};
    int n1 = sizeof(x)/32;

    double gradient;
    gradient = Gradient(x,n1);

    cout << "Gradient R1 xmin = " << Gradient[0] << endl;
}

Arrays are not first class elements in C++ language (they were not in C either). Arrays 不是 C++ 语言中的第一个 class 元素(它们也不在 Z0D61F8370CAD1D412F80B84D14 中)。 Specifically, when you pass an array to a function, or when you return it, it decays to a pointer to its first element.具体来说,当您将数组传递给 function 时,或者当您返回它时,它会衰减为指向其第一个元素的指针。 As the Grad array has automatic storage (neither static nor allocated) its lifetime ends at the end of a function and you only return a dangling pointer, meaning a pointer to a variable whose lifetime has ended.由于Grad数组具有自动存储(既没有 static 也没有分配),它的生命周期在 function 结束时结束,并且您只返回一个悬空指针,这意味着指向生命周期已结束的变量的指针。 Using it is explicitely Undefined Behaviour.使用它是明确的未定义行为。

In common implementation, automatic variables are allocated in the stack.在常见的实现中,自动变量被分配在堆栈中。 So after the function returns, the memory pointed to by the dangling pointer is likely to be reused and what you will get will not be what you would expect.所以在 function 返回后,悬空指针指向的 memory 很可能会被重用,而你得到的将不是你所期望的。 The segmentation fault is just one of the possible consequences of the UB.分段错误只是 UB 的可能后果之一。

The common way to return an array if you do not intend to use multi-threading would be to declare it static.如果您不打算使用多线程,则返回数组的常用方法是将其声明为 static。 That way its lifetime extends up to the end of the program and it solves the dangling pointer problem.这样,它的生命周期就一直延伸到程序结束,它解决了悬空指针问题。 That would be fine for a static size array (size defined at compile time) but not for a dynamic size (defined at run time).这对于 static 大小的数组(在编译时定义的大小)来说很好,但对于动态大小(在运行时定义)则不然。 So you are left with 2 C-ish ways:所以你有2种C-ish方式:

  • use a dynamically allocated array (with new[] or malloc );使用动态分配的数组(使用new[]malloc ); the caller will then have to free it (with resp. delete[] or free )然后调用者必须释放它(分别使用delete[]free
  • let the caller manage the array and pass it to the function ( void Gradient(const double x[], double *Grad, int n1) ).让调用者管理数组并将其传递给 function ( void Gradient(const double x[], double *Grad, int n1) )。 This is the prefered way because the caller has full control over the allocation mode.这是首选方式,因为调用者可以完全控制分配模式。

But in C++ the idiomatic way is to use a vector: std::vector Grad(n1*4, 0.);但是在 C++ 中,惯用的方法是使用向量: std::vector Grad(n1*4, 0.); . . A vector is a true C++ object and can be assigned or returned.向量是真正的 C++ object 并且可以被分配或返回。 Unless you have strong reasons to do so, avoid C-ish ways because C++ containers are much more programmer friendly.除非您有充分的理由这样做,否则请避免使用 C-ish 方式,因为 C++ 容器对程序员更友好。

I will try to help you我会尽力帮助你

  • variable-sized array double Grad [n1*4] = {0};可变大小数组double Grad [n1*4] = {0}; In C++, variable length arrays are not legal.在 C++ 中,变长 arrays 是不合法的。 G++ allows this as an "extension". G++ 允许将其作为“扩展”。
  • return Grad; return pointer to local data, after exiting function Gradient Grad id not available返回指向本地数据的指针,退出后 function Gradient Grad id 不可用

You can use std::vector , thus your code may look like this:您可以使用std::vector ,因此您的代码可能如下所示:

std::vector<double> Gradient(const double x[], int n1) {
    std::vector<double> Grad (n1*4, 0);
    ...
    Grad[i*4+3] = ...
    ...
    return Grad;
}

how can I return my array or write to a global variable如何返回我的数组或写入全局变量

Read a good book on C++ programming, and look into this C++ reference .阅读一本关于 C++ 编程的好书,并查看此C++ 参考

 double* Gradient(const double x[], int n1) { double Grad [n1*4] = {0};

If n1 is a large positive integer such as 1234567, your code is likely to have a stack overflow .如果n1是一个很大的正数integer比如1234567,那么你的代码很可能有栈溢出 If n1 is negative, you are in trouble.如果n1是负数,你就有麻烦了。 AFAIK, VLA s are not in C++. AFAIK, VLA不在 C++ 中。

Read alsohow to debug small programs另请阅读如何调试小程序

You probably want to use some standard C++ container .您可能想使用一些标准的 C++ 容器 std::array or std::vector comes to mind.想到std::arraystd::vector

You can return some std::array<int,10> .您可以return一些std::array<int,10> Of course the computer would copy ten integers, and that is slower than returning just a pointer.当然,计算机会复制十个整数,这比只返回一个指针要慢。

In some cases, you might want to use smart pointers .在某些情况下,您可能想要使用智能指针 Read about the standard <memory> header .阅读标准<memory> header

Beware of buffer overflow and segmentation fault and other kinds of undefined behavior .当心缓冲区溢出分段错误以及其他类型的未定义行为

If you compile your C++ code with a recent GCC compiler, enable all warnings and debug info, so use g++ -Wall -Wextra -g .如果您使用最近的GCC编译器编译 C++ 代码,请启用所有警告和调试信息,因此请使用g++ -Wall -Wextra -g If you use GCC 10 , consider using the recently addedstatic analysis options.如果您使用GCC 10 ,请考虑使用最近添加的static 分析选项。 If you prefer Clang , consider using its static analyzer .如果您更喜欢Clang ,请考虑使用其static 分析仪 Consider also using the Frama-C analyzer and reading this draft report.还可以考虑使用Frama-C分析器并阅读这份报告草稿 Be however aware of Rice's theorem .但是请注意赖斯定理

In all cases read the documentation of your particular C++ compiler .在所有情况下,请阅读您的特定 C++编译器的文档。 Don't confuse your C++ compiler with your IDE or source-code editor .不要将 C++ 编译器与IDE源代码编辑器混淆。 I suggest to compile on the command line, and use some build automation tool (perhaps GNU make or ninja ) with some version control tool such as git , and some debugger such as GDB .我建议在命令行上编译,并使用一些构建自动化工具(可能是GNU makeninja )和一些版本控制工具,如git和一些调试器,如GDB Tools like valgrind are also helpful.valgrind这样的工具也很有帮助。

Always avoid return ing the address of some automatic variable on the call stack .始终避免return调用堆栈上某些自动变量的地址。 Once your function returned, that address is invalid.一旦您的 function 返回,该地址就无效了。 Be scared of uninitialized pointer variables.害怕未初始化的指针变量。

There are multiple problems with your code.您的代码存在多个问题。

  1. You can't allocate the size of a static array at run time, that is you can't do this operation double Grad [n1*4] = {0};您无法在运行时分配 static 数组的大小,即您无法执行此操作double Grad [n1*4] = {0}; where n1 is a variable.其中 n1 是一个变量。 To allocate memory you have to use malloc function.要分配 memory,您必须使用 malloc function。 ptr = (int*)malloc(n * sizeof(int)); where n is the size of desired array.A continuous block of memory will be allocated其中 n 是所需数组的大小。将分配 memory 的连续块

  2. Array can't be returned as such, to solve that problem pointers are introduced.不能这样返回数组,以解决引入问题指针的问题。 If you follow the above method, ptr is a pointer which can access a memory location,while to access a particular element you can simple use ptr[i] , where i is the desired index如果您遵循上述方法, ptr 是一个指针,可以访问 memory 位置,而要访问特定元素,您可以简单地使用ptr[i] ,其中 i 是所需的索引

  3. Gradient is a function, it's illegal to perform this operation Gradient[0] . Gradient 是一个 function,执行这个操作Gradient[0]是非法的。 I hope this have cleared your doubt.我希望这已经消除了您的疑问。 A simple tip try writing small block of code to check if certain thing works.一个简单的提示尝试编写一小段代码来检查某些事情是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何编写一个程序来查找数组中的最小差异(未排序) c++ 只是 nlogn 时间复杂度 - how can i write a program for Find the smallest difference in array (not sorted) c++ just nlogn Temporal complexity 如何返回C ++数组? - How can i return an array c++? 如何在C ++中使用全局变量? - How can I use a global variable in C++? 如何在 c++ 中使用 function 访问全局变量? - How can i access global variable using function in c++? 如何在我的主程序c ++中使用我自己制作的Array头文件? - How can I use my own made Array header file in my main program c++? 如何在Python C / C ++扩展之间共享一个全局C / C ++变量? - How can I have a global C/C++ variable that is shared between Python C/C++ extensions? 如何用c ++编写映射程序 - How can write a mapping program in c++ 如何在不为 C++ 中创建临时变量的情况下返回数组或向量或映射? - How can I return an array or vector or map without creating a temporary variable for it in C++? 如果全局变量的声明引发异常,如何退出C ++程序? - How to exit a C++ program if the declaration of a global variable throws an exception? 如何返回指向我的二维数组的指针? C++ - How can i return a pointer to my 2d array? C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM