0

I have some 2d arrays written in C and I'm trying to call it from c++. I have managed to call a single dimension array (not quite sure how i did that) but I'm getting "segmentation fault (core dumped) error" when trying the same with 2d array. I assume it has some issues with pointers but currently I'm not at the level to understand what.

C Lib:

    #include <stdio.h>


void* fun(int *arr, int rows)
{


  for(int i=0; i<rows;i++)
    {
      arr[i]=2;
      printf("%d\n",arr[i]);
      //cout<<arr[i]<<endl;
    }

  return arr;
}



void* newfun(int **arr, int rows, int cols)
{

  for (int i=0; i<rows; i++)
  {
    for (int j=0; j<cols; j++)
    {
      arr[i][j] = 0;
      printf("%d\n",arr[i][j]);
    }
  }

  return arr;

}

c++ program:

    #include <iostream>

extern "C"
{
  #include "addnum.h"
}


using namespace std;

class singlematrix
{
  public:
    void* func(int *arr, int rows)
    {
      fun(arr,rows);
      return arr;
    }
};

class d2d
{
  public:
    void* func2(int **arr, int rows, int cols)
    {
      newfun(arr,rows,cols);
      return arr;
    }

};

int main(int argc, char *argv[]){

int *x1;
int **x;
int y=10;
int z=8;

singlematrix mx;
mx.func(x1,y);

//d2d mx2;
//mx2.func2(x,y,z);

  return 0;
}
  • 1
    You must allocate buffer before accessing that. – MikeCAT Aug 10 '20 at 07:27
  • 5
    It's just bad luck that the "one-dimensional" case appears to work; both have undefined behaviour. Your problems have nothing to do with mixing C and C++, but are caused by your not studying arrays and pointers. – molbdnilo Aug 10 '20 at 07:30
  • Study the basics of arrays and pointers in C before anything else. To begin with, a pointer is not an array and a pointer-to-pointer is not a 2D array. – Lundin Aug 10 '20 at 10:42

0 Answers0