I am trying to input 2d array from user, my array size is 6, but I am bale to input 7 elements. What is the error here? can you please also tell me how to input a 2d array from user using single pointer.
#include <stdio.h>
int main()
{
int a[2][3] = {0};
int i=0,j=0,l=0;
printf("enter 2d");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d\n",&a[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\n",a[i][j]);
}
}
return 0;
}
Here's my output:
./input2dusingsinglearray
enter 2d
1
2
3
4
5
6
7
1
2
3
4
5
6
The problem is with your scanf waiting for an extra intro, change to:
#include <stdio.h>
int main(void)
{
int a[2][3] = {0};
int i=0,j=0,l=0;
printf("enter 2d\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\n",a[i][j]);
}
}
return 0;
}
Also note that a 2d array must be initialized in this way:
int a[2][3] = {{0},{0}};
Turning your warnings on:
warning: missing braces around initializer [-Wmissing-braces]
Try using scanf("%d", &a[i][j]) instead of scanf("%d\n", &a[i][j]).
While the other answers are fine and correct, allow me to add my solution as well
#include <stdio.h>
#include <stdlib.h>
int main(){
size_t rows = 2;
size_t columns = 3;
int* matrix = (int *) malloc( rows * columns * sizeof(int));
printf("insert into 2d matrix[%d][%d]:\n", rows, columns);
int i = 0, j = 0;
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
scanf("%d", (matrix + (i * columns) + j));
}
}
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
printf("matrix[%d][%d] => %d\n", i, j, *(matrix + (i * columns) + j));
}
}
free(matrix);
return 0;
}
It dynamically allocate memory for 2d array and it can be an elegant solution if you want to pass pointer to a function.
I've faced the same problem yesterday and found that when we use extra space or any other thing it wants extra input. Then I've used the scanf function like down below.
scanf("%d",&a[i][j]);
Related
As suggested by a book of "Gottfried", I tried to input an array and display the contents of array in matrix form :
#include<stdio.h>
#define row 2
#define col 3
int main(){
int (*a)[col];
int i,j;
for(i=0;i<row;i++){
for(j=0;i<col;j++){
printf("Enter a(%d,%d)",i,j);
scanf("%d",(*(a+i)+j));
}
}
return 0;
}
I get the following output after inputting an element :
Segmentation fault (core dumped)
What is the problem in the code? Was it working in previous version of GCC so the writer wrote it down? What is the correct way to solve the problem with the same level of simplicity?
As it was pointed out in the comments it is not a 2D array, but a 1D array of pointers.
Also in the second for loop you accidently use i<col instead of j<col.
This will work
#include<stdio.h>
#define ROW 2
#define COL 3
int main(){
int a[ROW][COL];
int i, j;
for(i = 0; i < ROW; i++){
for(j = 0;j < COL; j++){
printf("Enter a(%d,%d)", i, j);
scanf("%d", (*(a + i ) + j));
}
}
return 0;
}
If you want to declare a as a pointer to an array of col ints, as it's done in this line
int (*a)[col];
Then you should also allocate (and ultimately free) the memory needed, before trying to use it.
a = malloc(sizeof(*a) * row);
if (!a)
exit(1);
// ...
free(a);
The posted code also have another issue in the nested loops
for (i = 0; i < row; i++) {
for (j = 0; i < col; j++) {
// ^^^^^^^ It should be 'j < col'
So i have this example:
3 4 6 11 4 6 38 7 6 9
I need to get from user several numbers and create multi dimension array.
The first number N (3 in my example) mean that my array (or matrix) will contain N² value and insert all this numbers (the next 9 values) into my array.
So first i need to define the array according my first value (3 in my example) and create my array:
int a[3][3];
The catch here is that i need to get all my input in a single line so i cannot use this:
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
scanf reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
scanf will store whole the input from stdin, so it really does not matter if it is in single line or not. The way for your code is just, simply ask user for dimensions and create the variable of the given dimension and fill each value with a scanf.
There are 3 ways to do it :
If your compiler supports variable length array:
int size,i,j;
scanf("%d",&size);
int matrix[size][size];
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
Does not support variable length array: (using array of pointers)
int size,i,j;
scanf("%d",&size);
int **matrix;
matrix = (int **)malloc(sizeof(int *) * size);
for(i=0;i<size;i++)
{
matrix[i] = (int *)malloc(sizeof(int) * size);
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
This looks easy but the way is very poor as it is not actually an 2D array but an array of pointers. hence, I suggest to use the 3rd way if your compiler does not support variable length array.
Using malloc: (with pointer)
Create Array of integers like:
int size;
scanf("%d",&size);
int *matrix;
matrix = (int *) malloc( sizeof(int) * size * size );
Now, to fill or get the values of the Array you need to traverse to the particular value.
to fill:
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (matrix + i*(size) + j));
}
}
to iterate: (print in this case)
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d " ,*(matrix+ i*size + j) );
}
printf("\n");
}
Note: It is very important to constrain the input and check whether it lies in some fixed range or not. for ex: ( 0 < size < 100). It is very simple and you can do it yourself. I have answered the important parts only :)
To begin with, you can't store 10 numbers in a 3x3 matrix. Always make sure your specification makes sense before you start programming.
Taking the input is trivial, just use a nested loop to control where the read input ends up in your matrix. Example with a fixed array size:
#include <stdio.h>
#include <stdlib.h>
#define x 3
#define y 3
int main (void)
{
int arr[x][y];
printf("Enter %d numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
(Note that this leaves a whole lot of junk like line feed characters behind in stdin. There's also no buffer overflow protection. See How to read / parse input in C? The FAQ for examples of how to read input properly.)
If you need a variable size matrix, you can use variable length arrays (VLA):
size_t x = 3; // some run-time value
size_t y = 3; // some run-time value
int arr[x][y];
... // then same code as above
Alternatively, you can use a dynamically allocated 2D array:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int (*arr)[y] = malloc( sizeof(int[x][y]) );
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
free(arr);
return 0;
}
Alternatively, if your compiler is from the Jurassic period, you can use old style "mangled" 2D arrays:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int* mangled = malloc(x * y * sizeof *mangled);
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &mangled[i*x + j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", mangled[i*x + j]);
}
printf("\n");
}
free(mangled);
return 0;
}
The above 4 alternatives are the only alternatives. You should not use "pointer-to-pointer look-up tables", there is absolutely no need for them here. Unfortunately, lots of bad books and bad teachers spread that technique. See Correctly allocating multi-dimensional arrays.
Try this:
int** InitMatrix()
{
int** matrix = NULL;
int n;
if (scanf("%d", &n) > 0 && n > 0)
{
matrix = malloc(n * sizeof(int*));
for (int i = 0; i < n; i++)
{
matrix[i] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
{
if (scanf("%d", &matrix[i][j]) == 0)
{
// user input error; decide what to do here
}
}
}
}
else
{
// user input error; decide what to do here
}
return matrix;
}
The program below is meant to print a square grid of integers based on the dimension which is inputted by the user (as part of the harvard cs50 course on edx).
The array is being initialized correctly, but when it comes to printing it out, the last column always prints incorrectly. I tried debugging by putting 2 printf statements in the innermost for loop of the init() function.
It seems that after the outermost loop runs once, the entry in the last column gets decremented by one, although it was correct just before this.
Why is this happening? Shouldn't it print correctly?
#include <stdio.h>
main()
{
void init(int dim, int arr[dim-1][dim-1]);
int dim;
printf("Enter board dimension(max 10): ");
scanf("%d", &dim);
int arr[dim-1][dim-1];
init(dim, arr);
int i,j;
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
printf("%2d ",arr[i][j]);
}
printf("\n");
}
}
void init(int dim, int arr[dim-1][dim-1])
{
int i,j,p;
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
arr[i][j] = (dim*dim-1)-i*dim-j;
}
for(p=0;p<dim;p++)
{
printf("%d ", arr[i][p]);
if(i>=1)
printf("%d ", arr[i-1][p]);
}
}
printf("\n");
if(dim%2==0)
{
arr[dim-1][dim-3] = 1;
arr[dim-1][dim-2] = 2;
}
}
EDIT: it should compile now
You define your array with a[dim - 1][dim - 1], which is one short of the desired dimension. If the user enters "4", you create a 3×3 array.
Your array is two-dimensional and of variable length. Therefore, you must pass the dimension alongside the array in functions, at least for the last dimension. You do this correctly, but the code in ´initbehaves as if the array werea[dim][dim], when it's actuallya[dim - 1][dim - 1]`.
Define the array with the actual dimension, dim and access the elements with indices 0 through dim - 1. This is usually done in a loop like this:
for (int i = 0; i < dim; i++) ...
Seeing >= or dim - 1 something similar should make you wary.
Your program now looks like this:
#include <stdio.h>
void init(int dim, int arr[dim-1][dim-1]);
void print(int dim, int arr[dim-1][dim-1]);
int main(void)
{
int dim;
printf("Enter board dimension: ");
scanf("%d", &dim);
int arr[dim][dim];
init(dim, arr);
print(dim, arr);
return 0;
}
void print(int dim, int arr[dim][dim])
{
int i,j;
for(i = 0; i < dim; i++) {
for(j = 0; j < dim; j++) {
printf("%2d ", arr[i][j]);
}
printf("\n");
}
}
void init(int dim, int arr[dim][dim])
{
int i, j;
for(i = 0; i < dim; i++) {
for(j = 0; j < dim; j++) {
int ii = dim - 1 - i;
int jj = dim - 1 - j;
arr[i][j] = ii*dim + jj;
}
}
}
I am trying to print a 2D array by passing it to a function, but I got weird results. Here is my code.
#include <stdio.h>
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray(b);
return 0;
}
void printArray(int (*ptr)[3])
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *((*ptr+i)+j));
}
printf("\n");
}
}
However, the output is
1 2 3
2 3 4
I think it is something to do with my 'j' variable but I can't seem to pinpoint it. Please help.
You need to apply the addition operator before using the dereference operator. You need to use parenthesis as the dereference operator(*) has higher precedence than the addition operator(+).
So, this
printf("%d\t", *((*ptr+i)+j));
should be
printf("%d\t", *((*(ptr+i))+j));
or better
printf("%d\t", ptr[i][j]);
Also, you need to move the function printArray before main or provide a function prototype before main like:
void printArray(int (*ptr)[3]);
You need to multiply i by 3 before adding j ...
printf("%d\t", *((*ptr+(i*3))+j));
Abandoning indexes in favor of pointers, assuming matrix is stored by rows (whic is normally the case):
#include <stdio.h>
void printArray(int *);
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int*)b);
return 0;
}
void printArray(int *ptr)
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *ptr++);
}
printf("\n");
}
}
Outputs:
1 2 3
4 5 6
printArray can take nb_column nb_line param and deal with all sort of 2D array
#include <stdio.h>
static void printArray(int *ptr, int nb_columns, int nb_lines)
{
int i, j;
for(i = 0; i < nb_lines; i++)
{
for(j = 0; j < nb_columns; j++)
{
printf("%d\t", *(ptr++));
}
printf("\n");
}
}
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int *)b, 3, 2);
return 0;
}
Here is my try. I am not totally sure about my manipulations with the pointer. Maybe this is why I am wrong, maybe there is some other case. I want to take the dimensions from the user and create a square matrix, make some manipulations with its elements, and display the original and results to the user. Last time I accomplished this by creating a 100x100 array, and specifying the end of each line, and end of lines by constants. Then I would print all the elements up to this constant. But it does not seem to be right to create a 100x100 array for 4x4 matrices. I could create a smaller array, but this does not seem to be the right solution to the problem. Is there a way in C to create a 2d array exactly the size specified by the users (it will be a square array). Thanks
#include <stdio.h>
#include <stdlib.h>
double * createMatrix(int dimentions);
void drawMatrix(double * matrix);
int main(void)
{
int n, i, j;
system("cls");
system("color 70");
system("pause");
puts("Enter the matrix's dimension");
scanf("%i", &n);
double * pmatrix = createMatrix(n);
for (i = 0; i < n; ++j)
for (j = 0; j < n; ++j)
{
printf("A%i%i: ", i + 1, j + 1);
scanf("%lf", pmatrix[i][j]);
getchar();
}
for (i = 0; i < n; ++i)
{
putchar('\n');
for (j = 0; j < n; ++j)
printf(" %lf ", &pmatrix[i][j]);
}
system("color 08");
return 0;
}
double * createMatrix(int n)
{
const int N = n;
const int N1 = N;
double matrix[N][N];
double * pmatrix = matrix;
return pmatrix;
}
You can create a matrix directly; you don't need a function for that. Replace the code
double * pmatrix = createMatrix(n);
by the regular way of declaring a 2-D array:
double matrix[n][n];
One more way of doing it using pointers.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
double **pmatrix;
int rowsize, colsize, i, j;
printf("Enter the number of rows: ");
scanf("%d",&rowsize);
printf("Enter the number of columns: ");
scanf("%d",&colsize);
//Allocate memory for 2D array
pmatrix = malloc(rowsize*sizeof(double*));
for(i=0;i<rowsize;i++)
{
pmatrix[i] = malloc(colsize*sizeof(int));
}
//Accepting the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("A %i %i: ", i + 1, j + 1);
scanf("%lf",&pmatrix[i][j]);
}
}
//Printing the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("%lf\t",pmatrix[i][j]);
}
printf("\n");
}
//Free the memory
for(i=0;i<rowsize;i++)
free(pmatrix[i]);
free(pmatrix);
return 0;
}