簡體   English   中英

將2D數組傳遞給函數

[英]Passing 2D array to a function

我有三個文件:array.cpp array.h array1.cpp

array.cpp將2維數組發送到array1.cpp中定義的函數。

問題是當我打印結果時,我得到了全零並且出現了末端分割錯誤。 請幫我哪里錯了?

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

這是問題所在:int cols; 2; 我認為應該是int cols = 2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM