Dipanjan Patra
Dipanjan Patra

Reputation: 59

2D array and pointer manipulation for matrix in C language

I'm doing a project to create a full matrix suit in C. Which could do most things related to matrix. I've already done it in Python successfully. But I'm trying to do it in C which is actually needed. The way I want to do it is create separate file for separate modules. But I'm really confused about arrays and pointers. I know pointers represent the address of that value.

What I want to do:

  1. Make a function module which asks for row n column number n then takes input of the matrix n then returns the array containing the matrix to another empty array so I could just call the function everytime I need a matrix input.

Things I don't understand:

  1. How to return an array from a function?

  2. or How to return a 2D pointer value from a function? or access it?

  3. Anything else wrong with my code?

Errors I'm getting:

  1. matrix_in.c:17:9: warning: return from incompatible pointer type [-Wincompatible-pointer-types]

  2. matrix.c:9:5: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]

  3. matrix.c:16:11: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int (*)[5]' [-Wformat=]

So far my code is as follows:

header /* header.h */

#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED

#define LIMIT_X 100
#define LIMIT_Y 100
int* matrix_in();

#endif

matrix_in /* matrix_in.c */

#include <stdio.h>
#include "header.h"

int* matrix_in()
{
    int i,j;
    //int* point;
    static int (*array)[LIMIT_X][LIMIT_Y];
    printf("please enter the elements:\n");
    for (i=0;i<2;i++)
    {
        for (j=0;j<2;j++)
        {
            scanf("%d",array[i][j]);
        }
    }
    return array;
}

matrix /* matrix.c */

#include <stdio.h>
#include "header.h"

int main()
{
    int m1[2][2],m2,i,j;
    int (*p1)[5][5];

    p1 = matrix_in();
    //p2 = matrix_in();

    for (i=0;i<2;i++)
    {
        for (j=0;j<2;j++)
        {
            printf("%d\t", *p1);
            p1++;
        }
    }   
    return 0;
}

Upvotes: 2

Views: 2981

Answers (3)

ameyCU
ameyCU

Reputation: 16607

If you want to take input in matrix you probably just need a 2-D array. Declaration would be this -

int array[n][n];  // 2-d array of integers

And this -

int (*p1)[5][5];  // p1 is a pointer to a 5 X 5-element array of int

Both the things are different. To return just declare a pointer , allocate memory and then return the pointer. And intead of this -

static int (*array)[LIMIT_X][LIMIT_Y];

you can declare like this -

static int array[LIMIT_X][LIMIT_Y];

And return array - return array;

This statement -

         `scanf("%d",array[i][j]);`
                     ^ & required here

Upvotes: 0

bpgeck
bpgeck

Reputation: 1624

If I'm correct is sounds as though you want to call a function that loads a matrix and then return this matrix to be stored in an array elsewhere.

The simple solution to your problem is that you write int (*p1)[5][5] which is actually a 3-dimensional array. It needs to be changed to a 2-D array like int** p1; which could then be filled using the code block below.

You have to change the return type in matrix_in(). Currently, you are attempting to return and int*, which is an 1-D array of ints. This needs to be changed to int**.

Edit:

So say for example I want a function that loads a 2-D array with a bunch of values and then return this array. I could write it as such:

Edit 2: Due to WhozCraig's comment I realized I needed to make some changes

Edit 3: Changed the code from c++ syntax to c syntax (got confused about the question sorry)

int** loadArray(int rows, int cols)
{
    int** array_to_return = (int**)malloc(rows * sizeof(int*)); // define one of two dimensions
    int value_to_increment = 0;

    for (int i = 0; i < rows; i++)
    {
        array_to_return[i] = (int*)malloc(cols * sizeof(int)); //define other dimension
    }

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            array_to_return[i][j] = value_to_increment; // fill each index with value
            value_to_increment++;
        }
    }

    return array_to_return;
}

This function loads an array with sequential values and then return the array. Now, since we malloc, you will need to free() the array at some point so as to avoid memory leaks.

Upvotes: 2

tonysdg
tonysdg

Reputation: 1385

Arrays in C are represented as a contiguous chunk of memory with a pointer pointing to the 0th element. Thus, an array generally looks like this:

---------------------
| 0 | 1 | 2 | 3 | 4 | //A five element array
---------------------
  ^
  |
pointer
to 0th
element

Notice that by pointing to the first element in the array, you can access the rest of the elements in the array by simply incrementing the pointer (known as pointer arithmetic). Thus, if int *a points to element 0, we know that we have to increment a four times to get to element 4.

2-dimensional arrays are a bit trickier; humans think of a 2-d array like this:

---------------------
| 0 | 1 | 2 | 3 | 4 |  //row 0
---------------------
| 0 | 1 | 2 | 3 | 4 |  //row 1
---------------------

However, computers have no notion of 2 dimensions in memory; a computer just sees (theoretically) one infinitely long row of memory. Thus, the computer arranges a 2-d array like this:

-----------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 
-----------------------------------------
  ^                   ^
  |                   |
row 0               row 1
begins              begins
here                here

This means the computer does some simple arithmetic with the modulus operator to access row 1:

a[x][y] = a[ (y * array_width) + x ]

So a[1][2] becomes a[1 * 5 + 2] = a[7].

This means that to pass a pointer to a 2-d array into a function, you still only need to pass the pointer to the 0th element in the array. You can then access the entire array as usual.

Other answers do a better job of explaining what exactly is wrong with your code - I just want to make sure you understand how arrays work in C :)

Upvotes: 1

Related Questions