Skip to content

Proper ways of returning dynamically allocated 2D array #1

Description

@msrumon

Problem is in this file. I have created algorithms for creating 2D arrays on-the-fly & printing a 2D array w/ functions. But they are not functioning as expected. To test it, I have created the following snippet (named TEST.c):

#include "./lib/matrix.h"

void main()
{
  /**
   * Test run 01
   */
  int test1[3][3];
  test1[0][0] = 1;
  test1[0][1] = 2;
  test1[0][2] = 3;
  test1[1][0] = 4;
  test1[1][1] = 5;
  test1[1][2] = 6;
  test1[2][0] = 7;
  test1[2][1] = 8;
  test1[2][2] = 9;
  spit(test1, 3, 3, "Spitting test-1:");

  /**
   * Test run 02
   */
  int **test2 = take(3, 3, "Taking test-2:");
  printf("\nPrinting test-2:\n");
  for (int r = 0; r < 3; r++)
  {
    printf("|");

    for (int c = 0; c < 3; c++)
    {
      if (c == 2)
        printf("%d", *((test2 + r) + c));
      else
        printf("%d\t", *((test2 + r) + c));
    }

    printf("|\n");
  }
}

And I get the following result:

TEST.c: In function 'main':
TEST.c:18:8: warning: passing argument 1 of 'spit' from incompatible pointer type [-Wincompatible-pointer-types]
   spit(test1, 3, 3, "Spitting test-1:");
        ^~~~~
In file included from TEST.c:1:
./lib/matrix.h:35:17: note: expected 'int **' but argument is of type 'int (*)[3]'
 void spit(int **matrix, const unsigned row, const unsigned column, const char *message)
           ~~~~~~^~~~~~

Spitting test-1: 
|1      3       5|
|3      5       7|
|5      7       9|

Taking test-2:
a11: 1
a12: 2
a13: 3
a21: 4
a22: 5
a23: 6
a31: 7
a32: 8
a33: 9

Printing test-2:
|1      4       7|
|4      7       8|
|7      8       9|

Need someone to help me out. If you are one of the experts, send a PR please.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

help wantedExtra attention is neededquestionFurther information is requested

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions