简体   繁体   English

仅使用指针将二维数组传递给函数并打印值

[英]passing 2d array into a function using only pointer and print the value

the result of this program (process 9164) exited with code -1073741819.该程序(进程 9164)的结果以代码 -1073741819 退出。 the program finished and nothing happens.....what should I do to make it run using only pointer without *x[] or x[][2]程序完成了,什么也没发生.....我应该怎么做才能让它只使用没有 *x[] 或 x[][2] 的指针运行

#include <iostream>
#include<string>
#include <fstream>
using namespace std;
void sum(int **x) {
    int s = 0;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cout << *(*(x + i) + j) << " ";
            s += *(*(x + i) + j);
        }
        cout << "\n";
    }
    cout << s;
}
int main() {
    int x[3][2] = { {11,15},{19,28},{5,8} };
    sum((int**)x);
    return 0;
}

Whenever you feel the need to do a C-style cast (like you do with (int**)x ) you should take that as a sign you're doing something wrong.每当您觉得需要进行 C 风格的转换时(就像您对(int**)x所做的那样),您应该将其视为您做错了什么。

An array of arrays is not the same as a pointer to a pointer.数组的数组是一样的指针的指针。

What happens is that you pass an invalid pointer, and the program will experience undefined behavior and crash .发生的情况是您传递了一个无效的指针,程序将遇到未定义的行为崩溃

What should happen is that the array x decay to a pointer to its first element, ie plain x is the same as &x[0] .应该发生的是数组x衰减到指向其第一个元素的指针,即普通x&x[0] That will be a pointer to an array , with the type int (*)[2] (in the case of x in your question).这将是一个指向数组的指针,类型为int (*)[2] (在您的问题中为x的情况下)。 That is the type you need to use for the function argument:这是您需要用于函数参数的类型:

void sum(int (*x)[2]) { ... }

And call like并像这样打电话

sum(x);

You can also generalize to accept any kind of "2D" array, by using template arguments for the dimensions and passing the array by reference:您还可以概括为接受任何类型的“2D”数组,方法是使用维度的模板参数并通过引用传递数组:

// For std::size_t
#include <cstdlib>

template<std::size_t A, std::size_t B>
void sum(int (&x)[A][B])
{
    // Use A and B as the sizes for the arrays...
    ...
}

While the above template version is better, the "proper" solution in C++ should be using std::array , as in:虽然上面的模板版本更好,但 C++ 中的“正确”解决方案应该使用std::array ,如下所示:

std::array<std::array<int, 2>, 3> = { ... };

and then pass it as a constant reference to the function.然后将其作为对函数的常量引用传递。

If the sizes aren't known at compile-time, or if the arrays should be dynamic, then use std::vector instead.如果在编译时不知道大小,或者数组应该是动态的,则使用std::vector代替。

A good book and and good teacher would teach these classes before going into pointers or C-style arrays.一本好书和好老师会在进入指针或 C 风格数组之前教授这些课程。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM