Printing 2d dynamically allocated array using pointer to pointer method - c

Here in this code I am trying to dynamically allocate memory to a 2d array and print it The problem I face here is I cant get the output properly lets assume my input is an 2d array of size 2*2 [1,2,3,4] but the output printed is [1,1,1,1].
#include <stdio.h>
#include <stdlib.h>
int output_func(int row, int col, int *ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
printf(" %d ", *ptr);
}
printf("|\n");
}
}
int main()
{
int **ptr;
int row, col;
int i, j;
printf("enter the no of rows for the matrix: ");
scanf("%d", &row);
printf("enter the no of col for the matrix: ");
scanf("%d", &col);
ptr = (int **)malloc(row * sizeof(int *));
for (int i = 0; i < row; i++)
{
ptr[i] = (int *)malloc(col * sizeof(int));
}
// input of first matrix
printf("\nEnter the elements for first matrix :\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("\t A[%d,%d] = ", i, j);
scanf("%d", &ptr[i][j]);
}
}
output_func(row, col, *ptr);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
// int* ptr -> int** ptr
void output_func(int row, int col, int** ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
// *ptr -> ptr[i][j]
printf(" %d ", ptr[i][j]);
}
printf("|\n");
}
}
int main()
{
int** ptr;
int row, col;
printf("enter the no of rows for the matrix: ");
scanf("%d", &row);
printf("enter the no of col for the matrix: ");
scanf("%d", &col);
ptr = (int**)malloc(row * sizeof(int*));
for (int i = 0; i < row; i++)
{
ptr[i] = (int*)malloc(col * sizeof(int));
}
// input of first matrix
printf("\nEnter the elements for first matrix :\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("\t A[%d,%d] = ", i, j);
scanf("%d", &ptr[i][j]);
}
}
output_func(row, col, ptr);
return 0;
}

If you want a function to print the array allocated using an array of pointers to arrays of int (also known as a jagged array), you must pass the pointer to the array of pointers.
In other words - this is wrong:
int output_func(int row, int col, int *ptr)
^^^^^^^^
A int-pointer but you want
a pointer to a pointer to int
which is "int **ptr"
So do
int output_func(int row, int col, int **ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
printf(" %d ", ptr[i][j]);
}
printf("|\n");
}
}
and call it like:
output_func(row, col, ptr);

Related

Functions in c language format transposing 2 arrays

So, my functions in my code don't talk to each other and I cannot for the life of me figure it out. What do you put in the parenthesis of the function headings. the variable names go in them but how are they formatted? Do I need pointers? If so can someone explain them. Thanks!
int FindTranspose(????)
int main(????)
FindTranspose (????)
#include <stdio.h>
int FindTranspose(int before[3][3], int after[3][3], int i, int j){
int rows, columns;
printf("\nThe orginial matrix: \n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++){
printf("%d ", before[i][j]);
}
}
for(rows = 0; rows < i; rows++){
for(columns = 0;columns < j; columns++){
after[columns][rows] = before[rows][columns];
}
}
printf("\n");
printf("\nThe Transpose of the matrix: \n");
printf("\n");
for(rows = 0; rows < j; rows++){
for(columns = 0; columns < i; columns++){
printf("%d ", after[rows][columns]);
}
printf("\n");
}
}
int main(){
int before[3][3], after[3][3], i, j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter number for array - [%d],[%d] : ",i,j);
scanf("%d", &before[i][j]);
}
}
FindTranspose (before[3][3], after[3][3], i, j);
return 0;
}
Picture of code
Picture of warnings
Dealing with multi-dimensional arrays as pointers is really tricky in C.
For example the multi-dimensional array before[3][3] defined in main:
The array name before is not "as usual" a pointer to before[0][0] although it's a pointer to before[0] so before actually has the type int (*) [3] which read as 'Pointer to a one-dimensional array of 3 elements'
Anyway, you should learn more about "pointer and multi-dimensional arrays".
For the moment here is the solution to your issue:
#include <stdio.h>
void FindTranspose(int (*before)[3], int (*after)[3], int i, int j){
int rows, columns;
printf("\nThe orginial matrix: \n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++){
printf("%d ", before[i][j]);
}
}
for(rows = 0; rows < i; rows++){
for(columns = 0;columns < j; columns++){
after[columns][rows] = before[rows][columns];
}
}
printf("\n");
printf("\nThe Transpose of the matrix: \n");
printf("\n");
for(rows = 0; rows < j; rows++){
for(columns = 0; columns < i; columns++){
printf("%d ", after[rows][columns]);
}
printf("\n");
}
}
int main(){
int before[3][3], after[3][3], i, j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter number for array - [%d],[%d] : ",i,j);
scanf("%d", &before[i][j]);
}
}
FindTranspose (before, after, i, j);
return 0;
}
Of course, there is an easier but complex to understand solution which is dealing with the multi-dimensional array as a one-dimensional array.
Here is an example of that:
#include <stdio.h>
#define NUM_OF_ROWS 3
#define NUM_OF_COLS 3
void FindTranspose(int *before){
int rows, columns, i;
int after[NUM_OF_ROWS][NUM_OF_COLS];
int *p, (*q)[NUM_OF_COLS];
printf("\nThe orginial matrix: \n");
i = 0;
for(p = before; p < before + NUM_OF_COLS * NUM_OF_ROWS; p++){
printf("%d ", *p);
if(++i >= NUM_OF_COLS){
i = 0;
printf("\n");
}
}
columns = 0;
for(p = before; p < before + NUM_OF_COLS * NUM_OF_ROWS;){
for(q = &after[0]; q < &after[NUM_OF_ROWS]; q++){
(*q)[columns] = *p++;
}
columns++;
}
printf("\n");
printf("\nThe Transpose of the matrix: \n");
for(rows = 0; rows < NUM_OF_ROWS; rows++){
for(columns = 0; columns < NUM_OF_COLS; columns++){
printf("%d ", after[rows][columns]);
}
printf("\n");
}
}
int main(){
int before[NUM_OF_ROWS][NUM_OF_COLS], i, j;
for(i=0; i<NUM_OF_ROWS; i++){
for(j=0; j<NUM_OF_COLS; j++){
printf("Enter number for array - [%d][%d]: ", i, j);
scanf("%d", &before[i][j]);
}
}
FindTranspose ( &before[0][0] );
return 0;
}
Recommended reading: C Programming A modern approach 2nd edition for K.N. King

Dynamic matrix initialization with scanf()

I need to make some functions for 2-dimensional arrays (a.k.a. matrixes) and the problem just starts with the first one.
I allocated the matrix in the heap memory using malloc() and then I tried to make a function that initializes the matrixes using a for loop of scanf()s, but after 3 times it takes the input, the program crashes.
Here is the code I made
void initMatrix(int **mat,int row,int col)
{
for(int i=0;i<row;i++){
printf("\n");
for(int j=0;j<col;i++){
printf("Cell (%d,%d): ",i,j);
scanf("%d",&mat[i][j]);
}
}
}
int main()
{
int r,c;
printf("Number of rows: ");
scanf("%d",&r);
printf("Number of columns: ");
scanf("%d",&c);
int **arr = (int **)malloc(sizeof(int*) * r);
for(int i=0;i<r;i++)
arr[i]=(int*)malloc(sizeof(int) * c);
// int count=0;
// for (int i = 0; i < r; i++)
// for (int j = 0; j < c; j++)
// arr[i][j] = ++count;
for (int i = 0; i < r; i++){
printf("\n");
for (int j = 0; j < c; j++)
printf("%d ", arr[i][j]);
}
initMatrix(arr,r,c);
printf("\n");
free(arr);
}
If I manually insert the content of the matrix, the program does work (without the initmatrix() function), I don't know why… I probably made a mistake somewhere.

Memory allocation for pointer to array and array of pointer

Below is the part of code I am stuck on. I want to dynamically allocate memory for
Pointer to array
Array of pointers
I am getting several error messages like invalid conversion from int * to int and so on.
Pointer to array
int (*array)[nrows][ncolumns];
array = (int*)malloc(nrows * ncolumns * sizeof(int));
printf("\n Enter the elements:\n");
for(i=0; i<nrows; i++)
{
for(j=0; j<ncolumns; j++)
{
scanf("%d", array[i][j]);
}
}
printf("Entered array is :\n\n");
for(i = 0;i<nrows; i++)
{
for(j = 0; j<ncolumns; j++)
{
if(j== ncolumns-1)
{
printf("%d \n", *array[i][j]);
}
else
{
printf("%d", *array[i][j]);
}
Array of pointers
int *array[nrows][ncolumns];
array[nrows][ncolumns] = (int*)malloc(nrows * ncolumns * sizeof(int));
printf("Enter elements:\n");
for(i = 0; i<nrows; i++)
{
for(j = 0; j<ncolumns;j++)
{
scanf("%d",&array[i][j]);
}
}
printf("Entered array is: \n");
for(i = 0; i<nrows; i++)
{
for(j = 0; j<ncolumns;j++)
{
if(j == ncolumns-1)
{
printf("%d \n",array[i][j]);
}
else
{
printf("%d \t",array[i][j]);
}
}
}
1> pointer to array
#include <stdio.h>
#include <stdlib.h>
int main(void){
int nrows = 3;
int ncolumns = 4;
int i, j;
int (*array)[nrows][ncolumns];//do you want <<int (*array)[ncolumns]>> ?
//like as int src[nrows][ncolumns]; array = &src;
array = malloc(nrows * ncolumns * sizeof(int));//(int*) : type mismatch
printf("\nEnter the elements:\n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns; j++){
scanf("%d", &(*array)[i][j]);
}
}
printf("Entered array is :\n\n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns; j++){
if(j != 0)
putchar(' ');
printf("%d", (*array)[i][j]);//need ( )
}
putchar('\n');
}
free(array);
return 0;
}
2> Array of pointers
#include <stdio.h>
#include <stdlib.h>
int main(void){
int nrows = 3;
int ncolumns = 4;
int i, j;
int *array[nrows][ncolumns];
int *src = (int*)malloc(nrows * ncolumns * sizeof(int));//no need (int*)
printf("Enter elements:\n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns;j++){
array[i][j] = &src[ i * ncolumns + j];//pointer pointed to entity (src[ i * ncolumns + j])
scanf("%d", array[i][j]);//type of array[i][j] is int *
}
}
printf("Entered array is: \n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns; j++){
if(j != 0)
putchar(' ');
printf("%d", *array[i][j]);//need * for dereference
}
putchar('\n');
}
free(src);
return 0;
}
3> option
#include <stdio.h>
#include <stdlib.h>
int main(void){
int nrows = 3;
int ncolumns = 4;
int i, j;
int (*array)[ncolumns];
array = (int (*)[ncolumns])malloc(nrows * sizeof(*array));//sizeof(*array) : sizeof(int[ncolumns])
printf("\nEnter the elements:\n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns; j++){
scanf("%d", &array[i][j]);
}
}
printf("Entered array is :\n\n");
for(i = 0; i<nrows; i++){
for(j = 0; j<ncolumns; j++){
if(j != 0)
putchar(' ');
printf("%d", array[i][j]);
}
putchar('\n');
}
free(array);
return 0;
}

How to print a 2d array with a function in C?

I'm trying to print a 2d array with a function, but I keep getting the error "pointer expected"
I'm trying to make a battleship-type grid. I'm fine with printing out the co-ordinate row and column, but I can't actually get the 2d array (which contains "." in every element) to print at all.
Any help would be appreciated, I'm very new to this. Thanks! :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board;
void board_setup(int *rows, int *columns){
char *invisible_board[*rows][*columns];
char *player_board[*rows][*columns];
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = "."; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = ".";
}
}
}
void display(int *rows, int *columns, char *invisible_board){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width,&invisible_board);
return (0);
}
this is the simplest changes I could make to your code to get you to working code.... now.... this isn't good code yet. But gets you started.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board[100][100]; // dynamically allocate....
char player_board[100][100]; // dynamically allocate....
void board_setup(int *rows, int *columns){
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = '.'; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = '.';
}
}
}
void display(int *rows, int *columns){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width);
return (0);
}

Ways to create dynamic matrix in C?

This is the only way I know to create a matrix (2D array) in C, dynamically, and reading user input into its elements:
Creating a pointer to an array of x pointers, where each pointer
represents a line in the matrix - x is the number of lines in the matrix (its height).
Pointing each pointer in this array to an array with y elements,
where y is the number of columns in the matrix (the width).
int main()
{
int i, j, lines, columns, **intMatrix;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
intMatrix = (int **)malloc(lines * sizeof(int *));
//pointer to an array of [lines] pointers
for (i = 0; i < lines; ++i)
intMatrix[i] = (int *)malloc(columns * sizeof(int));
//pointer to a single array with [columns] integers
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i][j]);
}
}
Are there other ways to do this?
You can try like this
int main()
{
int i, j, lines, columns, *intMatrix;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
intMatrix = (int *)malloc(lines * columns * sizeof(int));
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i*lines + j]);
}
}
From C99 onwards (but not C++), you can use variable length arrays:
int main()
{
int i, j, lines, columns;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
{
int intMatrix[lines][columns];
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i][j]);
}
}
}
}
Or even like this:
void readData (int lines, int columns, int array[lines][columns])
{
int i, j;
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &array[i][j]);
}
}
}
int main()
{
int lines, columns;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
{
int intMatrix[lines][columns];
readData (lines, columns, intMatrix);
}
}
But, in both cases, the array data is all stored on the stack, not the heap, so there's no way to store it properly, and you can't put it in a struct or anything malloc'd.
struct matrix {
type *mem;
};
struct matrix* matrix_new () {
struct matrix *M = malloc (sizeof(matrix));
M->mem = malloc (sizeof (type) * rows * cols);
return M;
}
use realloc,memcpy,memmove and free to modify chunks of the array. To access single elemnts use something like mem[row*cols+col] or mem[rows*col+row] depend on what has priority for you (or what you define a row and a column).

Resources