How to print a 2D array? - arrays

I have two functions. One that creates a multiplication table of a given number and the other function prints the array out. Below is my code:
Here's the error (Line 18):
expression must be a pointer to a complete object type
How do I fix this error and print the array? Also, I don't know how to print a new line after every row.
#include "multiplication.h"
#include <stdio.h>
int arr[][];
void mulitpication(int num){
/* initialize array and build*/
int arr[num][num];
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int arr[][]){
/* print the arr*/
int i;
for(i=0;i<sizeof(arr);i++){
for(int j=0;j<sizeof(arr);j++){
printf("%d ",arr[i][j])**(line 18)**;
}
}
}

If using C99 or later with VLA support, pass into the print function the dimensions needed.
// void print(int arr[][]){
void print(size_t rows, size_t cols, int arr[row][col]){
size_t r,c;
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ",arr[r][c]);
}
printf("\n");
}
}

You need to declare the array in main(), so it can be passed to both functions.
When an array is passed as a function parameter, it just passes a pointer. You need to pass the array dimensions, they can't be determined using sizeof.
To get each row of the table on a new line, put printf("\n"); after the loop that prints a row.
#include <stdio.h>
void multiplication(int num, arr[num][num]){
/* initialize array and build*/
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int num, int arr[num][num]){
/* print the arr*/
int i;
for(i=0;i<num;i++){
for(int j=0;j<num;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main(void) {
int size;
printf("How big is the multiplication table? ");
scanf("%d", &size);
int arr[size][size];
multiplication(size, arr);
print(size, arr);
return 0;
}

Related

Why don't I see any output if I try to print this 2D array using pointer to pointer?

I am trying to use pointer to pointer to access a 2D array from a function. But when I run the code it compiles successfully but does not show any output. I can't get where the problem is.
#include <stdio.h>
#define m 3
#define n 5
void print_2D_mat(int **arr)
{
for(int i=0;i<m;i++){
for(int j=0;j<n;j++) printf("%d ",*(*(arr+i)+j));
printf("\n");
}
}
int main()
{
int arr[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++) scanf("%d",&arr[i][j]);
print_2D_mat(arr);
return 0;
}
when you pass a pointer as **arr it doesnt have the information of columns. so it cant stride row wise. correct the code as follows,
#include <stdio.h>
#define m 3
#define n 5
void print_2D_mat(int (*arr)[n])
{
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{
printf("%d ",*(*(arr+i)+j));
};
printf("\n");
}
}
int main()
{
int arr[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
scanf("%d",&arr[i][j]);
}
}
print_2D_mat(arr);
return 0;
}

How to pass a dynamically allocated contiguous 2D array with user-decided size to a function in C11?

In my main function, I allocate a 2D contiguous array with equal number of rows and columns that are decided by the user:
#include <stdio.h>
#include <stdlib.h>
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
}
I then want to pass this matrix and the d value to a function that will fill it with numbers from 1 to d*d and then print it:
void fillMatrix(int d, /*matrix*/)
How should I pass the matrix to the function? I don't have trouble with the rest of the function per se, but I don't seem to be able to properly pass the matrix in order to then fill it as a generic 2d array with the line array[i][j]= value. From what CLion is telling me, I seem to be working wrong with the fact that it's a int(*)[d], as it often tells me that I'm passing an incompatible pointer when I try to actually call the function.
Some things I tried and didn't work:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix(int, int*);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, (int *) matrix);
}
void fillMatrix(int d, int *matrix){
int i=0, j=0, k=1;
for(i=0;i<d;i++){
for(j=0;j<d;j++){
matrix[i][j]= k;
k++;
}
}
}
Here, when I try to do matrix[i][j]= k;, I get the error "Subscripted value is not an array, pointer, or vector ", and changing matrix to *matrix doesn't help
#include <stdio.h>
#include <stdlib.h>
void fillMatrix(int, int*);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, matrix);
}
Here, when calling the function, I get the error "Incompatible pointer types passing 'int (*)[d]' to parameter of type 'int *' "
And when I try to write void fillMatrix(int, int[][]);, I get the error "Array has incomplete element type 'int []' "
Finally, if I do:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix(int, int[][0]);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, matrix);
}
void fillMatrix(int d, int matrix[][0]){
int i=0, j=0, k=1;
for(i=0;i<d;i++){
for(j=0;j<d;j++){
matrix[i][j]= k;
k++;
}
}
for(i=0;i<d;i++){
for(j=0;j<d;j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
it won't print the proper k value.
The most correct form is this:
int(*matrix)[d][d] = malloc( sizeof(int[d][d]) );
Here it is pretty clear that we are declaring a pointer to a square 2D array of int. However, the reason why this form isn't often used is because de-referencing turns cumbersome: (*matrix)[i][j]. To skip this extra de-referencing, a handy trick is to drop one dimension out of the pointer declaration (and that's what your current code does too):
int(*matrix)[d] = malloc( sizeof(int[d][d]) );
Now we can do a readable matrix[i][j] as expected.
As for how to declare a function, just declare it as using a 2D array because that's what you want:
void fillMatrix (size_t size, int matrix[size][size]);
Now this decays to a pointer to the first element and what is the type of such a pointer? Since the first element is of type int [size] and a pointer to it is int(*)[size], we actually end up with the very same type as was used in main, 100% compatible.
Full example:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix (size_t size, int matrix[size][size])
{
int k=1;
for(size_t i=0; i<size; i++)
{
for(size_t j=0; j<size; j++)
{
matrix[i][j] = k++;
}
}
}
void printMatrix (size_t size, int matrix[size][size])
{
for(size_t i=0; i<size; i++)
{
for(size_t j=0; j<size; j++)
{
printf("%2.d ", matrix[i][j]);
}
puts("");
}
}
int main (void)
{
size_t size=5;
int(*matrix)[size] = malloc( sizeof(int[size][size]) );
fillMatrix(size, matrix);
printMatrix(size, matrix);
free(matrix);
}
Further study: Correctly allocating multi-dimensional arrays

Printing array elements as difference between the max value of the array

I wrote a program to get an array which will return an array with elements as difference between max value and remaining elements.
#include <stdio.h>
void behind(int *, int);
int main(void) {
int array[10];
int N, i;
scanf("%d", &N);
for (i=0; i<N; i++) {
scanf("%d", &array[i]);
}
behind(array, N);
for (i=0; i<N; i++) {
printf("%d\n", array[i]);
}
return 0;
}
void behind(int *ptr,int size) /* Write your function behind() here: */
{
int i,max=0;
for(i=1;i<size;i++){
if(ptr[i-1]>=ptr[i])
max=ptr[i-1];
else
max = ptr[i];
}
for(i=0;i<size;i++);
ptr[i]=max-ptr[i];
}
why my program always return the same array that I got as input?

how do returns a matrix in C (include code)

i defined a matrix into a function. how do i return that matrix for print it when i call it with another function. i mean...
#include<stdio.h>
#include<conio.h>
#include<time.h>
void main() {
int m,n;
printf("type 2 numbers:");
scanf("%i %i",&m,&n);
declaration(m,n);\\HERE IS THE PROBLEM
printing(matrix,m,n);
getch();
}
void declaration(int a,int b) {
srand(time(NULL));
int i,j,matrix[a][b];
for(i=0;i<a;i++){
for(j=0;j<b;j++){
matrix[i][j]=1+rand()%7;
}
}
}
void printing(int c[100][100],int a,int b) {
int i,j;
for(i=0;i<a;i++){
for(j=0;j<b;j++){
printf("%i\t",c[i][j]);
}
printf("\n");
}
}
Define it like:
typedef struct {
int rows;
int cols;
int *data;
} int_matrix_entity, *int_matrix;
int_matrix int_matrix_create(int rows, int cols, bool rand)
{
int_matrix mt;
int i;
if ((mt = malloc(sizeof(int_matrix_entity))) == NULL)
{
return NULL;
}
if ((mt->data = malloc(sizeof(int) * cols * rows)) == NULL)
{
free(mt);
return NULL;
}
if (rand)
{
srand(time(NULL));
for (i = 0; i < cols * rows; i++)
{
mt->data[i] = 1 + rand() % 7;
}
}
else
{
memset(mt->data, 0, sizeof(int) * cols * rows);
}
return mt;
}
void int_matrix_printf(int_matrix mt)
{
int i;
int j;
for (i = 0; i < mt->rows; i++)
{
for (j = 0; j < mt->cols; j++)
{
printf("%5d ", mt[i * cols + j]);
}
printf("\n");
}
}
You have a few points that require a bit more attention;
1 ) read warning and error messages given by your compiler
2 ) again, read warning messages given by your compiler
3 ) use indentation to make your code more readable.
4 ) Always return from main(), that's a good practice
The code below does what you want to achieve; have a look at it and keep on reading...
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// You either have to declare your functions
// or implement them before main()
void declaration(int a,int b, int m[a][b]);
void printing(int a,int b, int m[a][b]);
int main(){ // always return from main()
int m,n;
printf("type 2 numbers:");
scanf("%i %i",&m,&n);
int matrix[m][n];
declaration(m, n, matrix);
printing(m, n, matrix);
return 0;
}
void declaration(int a,int b, int m[a][b]){
srand(time(NULL));
int i,j;
for(i=0;i<a;i++){
for(j=0;j<b;j++){
m[i][j]=1+rand()%7;
}
}
}
void printing(int a,int b, int m[a][b]){
int i,j;
for(i=0;i<a;i++){
for(j=0;j<b;j++){
printf("%i\t",m[i][j]);
}
printf("\n");
}
}
You need a way to transfer data from one function to another. You cannot simply declare an auto variable in one function and pass it to another as you did in the code below
declaration(m,n);
printing(matrix,m,n); /* where does matrix[][] come from? */
remember, C is a strongly typed language which means you have to declare your variables before using them. This applies to your functions as well. You either have to give your function declarations before main() (or more specifically, before using them), or implement them.
Look into your header files (i.e. .h files) and you will see lots of function declarations.
Since you use variable length arrays, make sure your compiler is at least capable of compiling code confirming C99 standard.
Some extras;
Normally, C passes arguments by value and you have to use a pointer if you want the value of your variable get changed within the function. If you have a close look at the code snippet I gave, I simply used an int m[a][b].In C, the name of an array is a pointer to its first element, hence you can change the value of array elements when actually array's name is passed to your function as an argument.
For further reading, you may want to look at
variable scope
global variables (you can define matrix[][] as a global variable and change the value of matrix elements)
declaration vs definition in C
Another simple way to do it is use double pointer to create 2-dimensional array. Keep it simple.
#include <stdio.h>
#include <stdlib.h>
int** create_matrix(int rows, int cols) {
int **matrix = malloc(rows*(sizeof(int *)));
for(int i = 0; i < rows; i++) {
matrix[i] = malloc(cols*sizeof(int));
}
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
matrix[i][j] = 1 + rand()%7;
}
}
return matrix;
}
void printing(int** matrix, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void) {
int rows, cols;
rows = 3, cols = 3;
int** matrix = create_matrix(rows, cols);
printing(matrix, rows, cols);
free(matrix);
return 0;
}

using #define in functions

How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.

Resources