-1

This code takes 3 parameters as input.

Input : InitialValue, Row, Col

Output : 2D array

Ex: Input 1, 3, 3

Output :

1 2 3

4 5 6

7 8 9

Where am i going wrong here ? Is there any better way to modify whatever i've written

#include<bits/stdc++.h>
using namespace std;
int** func(int s,int r,int c);


int main()
{
 int s,row,col;
 cin >> s >> row>> col;
 int** res;
 res = func(s,row,col);

for(int i=0;i<row;i++)
{
 for(int j=0;j<col;j++)
  {
  cout << res[i][j]<<" ";
  }
 cout << endl;
}
 return 0;
}

int** func(int s,int r,int c)
 {
  int** arr;
  for(int i=0;i<r;i++)
  {
   for(int j=0;j<c;j++)
   {
     arr[i][j]=s;
     s = s+1;
    }
  }
   return arr;
 }
David Gladson
  • 547
  • 9
  • 17

2 Answers2

0

You have to use malloc for arr.

int **arr = (int **) malloc(r * sizeof(int **));
for(int k = 0; k<c; k++)
    arr[k] = (int *) malloc(sizeof(int))

Then you can use new

int **arr = new int*[r];
for(int k = 0; k<c; k++)
    arr[k] = new int[c];

And don't forget to use delete.

rayo
  • 1
  • 1
  • 1
  • 1
0

What about something like this?

#include <iostream>
#include <memory>

void FillArray(int start, int rows, int cols, std::unique_ptr<int[]> &result)
{
    int size = rows * cols;
    result = std::make_unique<int[]>(size);
    for (int i = 0; i < size; ++i)
        result[i] = start + i;
}

void PrintArray(int rows, int cols, std::unique_ptr<int[]> &arr)
{
    int size = rows * cols;
    for (int i = 0; i < size; ++i)
        std::cout << (i % cols == 0 ? "\n" : " ") << arr[i];

    std::cout << std::endl;
}

int main()
{

    int start, rows, cols;
    std::unique_ptr<int[]> arr;

    std::cout << "Enter params (start cols rows): ";
    std::cin >> start >> cols >> rows;

    FillArray(start, rows, cols, arr);
    PrintArray(rows, cols, arr);

    return 0;
}

For example:

Enter params (start cols rows): 10 10 5

10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37