0

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 
8
  • 4
    I think you meant "int cols=2;" not "int cols;2;" - with the current code, cols is uninitialized. Commented Dec 31, 2013 at 6:25
  • I think test3 causes undefined behavior. Commented Dec 31, 2013 at 6:26
  • @CharlieTangora thank u for pointing it out. DOn't know why I didn't noticed it first.. Commented Dec 31, 2013 at 6:28
  • This code doesn't compile. Is a minimal complete example too much to ask? Commented Dec 31, 2013 at 6:29
  • 4
    Also, you should not use free use delete[] in this case Commented Dec 31, 2013 at 6:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Rikayan, Charlie and I posted at the same time.
@RikayanBandyopadhyay: He wrote it as a comment, though. If you snooze you lose.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.