简体   繁体   中英

Passing 2D array to a function

I have three files: array.cpp array.h array1.cpp

array.cpp sends a 2 dimentional array to the function defined in array1.cpp.

Problem is when I print the results then I get all zeros and in the end segmentation fault. Please help me where I am doing wrong?

array1.cpp

#include <iostream>

#include <stdlib.h>
#include <cstring>
#include "array1.h"


using namespace std;

void test3(int **b, int rows, int cols);


void test3(int **b, int rows, int cols){

for (int i=0 ;i< rows; i++)
{
  for(int j=0;j<cols;j++){

  cout << b[i][j] << endl;
}
}}

array.cpp

#include <iostream>

#include "array1.h"

 using namespace std;

 void test3(int **b, int rows, int cols);


int main() {

 int **a;
 a = new int*[3];

for(int i = 0; i < 3; ++i)
 {
   a[i] = new int[2]; } 

    for(int StateNum=0; StateNum<3; StateNum++  ) 
                                      {

                                           a[StateNum][0]=4;
                                           a[StateNum][1]=3;
                                      }
    int rows=3;
    int cols;2;
    cout << "popppp" << endl;  
    test3(a,rows,cols);

    for (int i=0;i< rows;i++)
     {
      free (a[i]);
      }
       free(a);
     return 0;
   }

array1.h

#ifndef ARRAY1_H_
#define ARRAY1_H_
 #include <string>

 using namespace std;

 void test3(int **b, int rows, int cols);

 #endif

Here is the problem: int cols;2; I think it should be int cols = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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