Printing a 2D array in C
Is this any help?
#include <stdio.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
Print a 2D array as a grid in C
You can just add a newline to your print loop, see below:
printf("Two Dimensional array elements:\n");
for(i=0; i<rowSize; i++) {
for(j=0; j<colSize; j++) {
printf("%d ", disp[i][j]);
}
printf("\n"); // <<<<<< added newline
}
Example printout from running the code:
Two Dimensional array elements:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Even better if you add some alignment with tabs - simply use printf("%d\t", disp[i][j]);
, result:
Two Dimensional array elements:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Print 2D Array as a Method in C++
Your array is actually flat, meaning that you have to cast its type to int*
, not to int**
. int**
refers to array of pointers to int arrays, but you have no pointers inside array.
In other words you have actually 1-dimensional array of ints (flat). Any C multi-dimensional array like int a[3][5]
or int a[3][5][7]
are all flat array, 1-dimensional in nature. [3][5]
array points to contiguous region in memory containing 3 * 5 = 15
ints, and [3][5][7]
array points to 3 * 5 * 7 = 105
ints in contiguous region of memory.
Also after casting to int*
information about dimensions is lost, hence you have to do indexing arithmetics manually through using [i * col + j]
:
Try it online!
#include <iostream>
using namespace std;
void printArray2D(int* list, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << list[i * col + j] << " ";
}
cout << endl;
}
}
int main()
{
int list1[2][2] = { {1,2},{3,4} };
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
printArray2D((int*)list1, row1, col1);
return 0;
}
Output:
1 2
3 4
Actually there is a C++ specific solution using templates that can be used to keep information about dimensions and forward this information to function, then you don't have to use manual indexing arithmetics:
Try it online!
#include <iostream>
using namespace std;
template <int Rows, int Cols>
void printArray2D(int const (&list)[Rows][Cols]) {
for (int i = 0; i < Rows; i++) {
for (int j = 0; j < Cols; j++) {
cout << list[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int list1[2][2] = { {1,2},{3,4} };
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
printArray2D(list1);
return 0;
}
Output:
1 2
3 4
Another nice solution in case if you have fixed multi-dimensional array is by using std::array. Then you don't need to forward any dimensions information, just use .size()
method of std::array
:
Try it online!
#include <iostream>
#include <array>
template <typename ArrT>
void printArray2D(ArrT const & list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list[i].size(); j++) {
std::cout << list[i][j] << " ";
}
std::cout << std::endl;
}
}
int main()
{
std::array<std::array<int, 2>, 2> list1 =
{ std::array{1,2}, std::array{3,4} };
printArray2D(list1);
return 0;
}
Output:
1 2
3 4
How to print a 2D array with dots inside them in C
Sometimes, while troubleshooting a seemingly impossible problem, it is a good idea to remove all distractions from the code:
Run a simplified main()
function:
int main(int argc, char *argv[])
{
initialise_board();
//while (!check_win()) {
display_board();
// get_move(turn);
// turn = (turn == 1) ? 2 : 1;
return 0;
}
And you will see some output, which you can then debug to adjust as needed.
However, As you point out in your comments, you are not seeing output. If you look closely, you will discover that is because you are never including cpuBoard
or playerBoard
in a printf statement, such as:
printf("%c", cpuBoard[i][j]);
The following will not finish this for you, but will get you started:
void display_board(void)
{
//printf("\n");//removed for illustration
//for (char i = 'A'; i < 'H' + 1; i++) {
// printf("%c", i);
//}
printf("\n");
for (i = 1; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
printf("%c", cpuBoard[i][j]); //illustrates printout of populated array cpuboard.
}
printf("\n");
}
printf("===");
printf("\n");
}
Use of a function on a 2d array
- The function
int function(int **arr)
does not return anint
so make itvoid
. - When you call it,
a = function(&arr[i][0]);
, you do not usea
after the assignment. I suggest that you removea
from the program completely since it's not used anywhere. - The call to the function,
function(&arr[i][0]);
, should simply befunction(arr);
- The function signature needs to include the extent of all but the outermost dimension:
void function(int arr[][M])
- Inside the function, you use
3
and5
instead ofN
andM
. That accesses the array out of bounds. - In
function
, thei
andj
you declare at the start of the function are unused. Remove them. arr[i][j] = arr[i][j] + 50;
is better written asarr[i][j] += 50;
- When initializing a multidimensional array, use braces to make it simpler to read the code:
int arr[N][M] = {{10, 11, 12, 13}, {14, 15, 16, 17}};
- In
main
you mixint
andsize_t
for the indexing variables. I suggest you settle for one type. - Remove unused header files (
string.h
)
Example:
#include <stdio.h>
#define N 2
#define M 4
void function(int arr[][M]) {
for(int i = 0; i < N; i++) {
for(size_t j = 0; j < M; j++) {
arr[i][j] += 50;
}
}
}
int main() {
int arr[N][M] = {{10, 11, 12, 13}, {14, 15, 16, 17}};
for(size_t i = 0; i < N; i++) {
for(size_t j = 0; j < M; j++) {
printf("value of arr[%zu][%zu] is %d\n", i, j, arr[i][j]);
}
}
printf("\n ***values after modification***\n");
function(arr);
// int array print results
for(size_t i = 0; i < N; i++) {
for(size_t j = 0; j < M; j++) {
printf("value of arr[%zu][%zu] is %d\n", i, j, arr[i][j]);
}
}
}
Since you print the array more than once, you could also add a function to do so to not have to repeat that code in main
:
void print(int arr[][M]) {
for(size_t i = 0; i < N; i++) {
for(size_t j = 0; j < M; j++) {
printf("value of arr[%zu][%zu] is %d\n", i, j, arr[i][j]);
}
}
}
How can I print multidimensional arrays in C?
Use nested for loops. For example
for ( size_t i = 0; i < 3; i++ )
{
for ( size_t j = 0; j < 4; j++ )
{
printf( "%2d ", number[i][j] );
}
putchar( '\n' );
}
Pay attention to that it is a bad idea to use magic numbers like 3
and 4
. Instead use named constants.
As for the conversion specifier %s
then it is used to output one-dimensional character arrays that contain strings
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
enum { M = 3, N = 4 };
int number[M][N] =
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 },
};
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%2d ", number[i][j] );
}
putchar( '\n' );
}
return 0;
}
Its output is
10 20 30 40
15 25 35 45
47 48 49 50
To output a two-dimensional integer array as a one-dimensional integer array apply casting to the array designator to the type int *
or const int *
.
For example
#include <stdio.h>
int main(void)
{
enum { M = 3, N = 4 };
int number[M][N] =
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 },
};
const int *p = ( const int * )number;
for ( size_t i = 0; i < M * N; i++ )
{
printf( "%2d ", p[i] );
}
putchar( '\n' );
return 0;
}
The program output is
10 20 30 40 15 25 35 45 47 48 49 50
And vice versa to print a one dimensional array as a two-dimensional array use the following approach.
#include <stdio.h>
int main(void)
{
enum { N = 12 };
int number[N] = { 10, 20, 30, 40, 15, 25, 35, 45, 47, 48, 49, 50 };
size_t rows = 3, cols = 4;
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ )
{
printf( "%2d ", number[i * cols + j] );
}
putchar( '\n' );
}
return 0;
}
The program output is
10 20 30 40
15 25 35 45
47 48 49 50
How to print values down a column in a 2D array in C?
You simply need to swap i
and j
for the dimensions when addressing a certain element of the array in the caller.
int* averageIncome(int size, int size_2, int arr[][size_2]) {
int* t_arr = calloc(4, sizeof(int)); // calloc to initialize the array elements to 0.
if ( t_arr == NULL )
{
fputs("Error at memory allocation for t_arr!", stderr);
exit(1);
}
int avg = 0; // definition of avg placed outside of the loop.
for (int i = 0; i < size_2; i++) {
for (int j = 0; j < size; j++) {
printf("%d\n", arr[j][i]); // j swapped with i.
avg += arr[j][i]; // same here too.
}
printf("-----\n");
t_arr[i] = avg / size;
avg = 0;
}
return t_arr;
}
Example (Online):
#include <stdio.h>
#include <stdlib.h>
#define ROWS 4
#define COLS 3
int* averageIncome(int size, int size_2, int arr[][size_2]) {
int* t_arr = calloc(4, sizeof(int)); // calloc to initialize the array elements to 0.
int avg = 0; // definition of avg placed outside of the loop.
for (int i = 0; i < size_2; i++) {
for (int j = 0; j < size; j++) {
printf("%d\n", arr[j][i]); // j swapped with i.
avg += arr[j][i]; // same here too.
}
printf("-----\n");
t_arr[i] = avg / size;
avg = 0;
}
return t_arr;
}
int main (void)
{
int censusData[ROWS][COLS] = {
{87290, 77787, 55632},
{83020, 78373, 62314},
{95588, 87934, 705421},
{112456, 97657, 809767}
};
int* p = averageIncome(ROWS, COLS, censusData);
for ( int i = 0; i < COLS; i++ )
{
printf("Average Income of %d. column is: %d\n", i + 1, p[i]);
}
return 0;
}
Output:
87290
83020
95588
112456
-----
77787
78373
87934
97657
-----
55632
62314
705421
809767
-----
Average Income of 1. column is: 94588
Average Income of 2. column is: 85437
Average Income of 3. column is: 408283
Side notes:
Always check the returned pointer from a memory-management for a null pointer if the allocation failed.
I used
calloc()
instead ofmalloc()
to initialize all elements of the dynamically allocated array to 0.The definition of
avg
should be placed before the nested loops, not within. Resetavg
to0
at the end of the outer loop.avg /= size_2; t_arr[i] = avg;
should beavg /= size; t_arr[i] = avg;
. Note the replacement ofsize_2
withsize
.avg /= size; t_arr[i] = avg;
can be simplified byt_arr[i] = avg / size;
.
Related Topics
Serializing Opencv Mat_<Vec3F>
Setjmp/Longjmp: Why Is This Throwing a Segfault
Same Random Numbers Every Time I Run the Program
Std::Vector of Std::Vectors Contiguity
Std::Vector to String with Custom Delimiter
Why the Sizeof(Bool) Is Not Defined to Be One, by the Standard Itself
Understanding the List Operator (%) in Boost.Spirit
Using Boost::Iostreams::Mapped_File_Source with Std::Multimap
Easiest Way of Using Min Priority Queue with Key Update in C++
Address-Of Operator (&) VS Reference Operator(&)
How to Restart My Own Qt Application
Cast Vector<T> to Vector<Const T>
When Extending a Padded Struct, Why Can't Extra Fields Be Placed in the Tail Padding