C Segmentation Fault While using scanf for 2D array - c

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'

Related

User input from one line into multi dimention array

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;
}

Segmentation fault, first time with 2D arrays

I am working with 2D arrays for the first time for a sudoku checker program; below is my code.
My program compiles without error, but when I run it, it gives me a segmentation fault.
It has been a while since I last coded, so I am unsure what I'm missing. I've also never had to deal with this error before.
My Code:
#include <stdio.h>
#include <stdlib.h>
int sudokuCheck();
int arrayMake();
#define SIZE 9
int main(){
int sudokAmount;
printf("Please Enter the amount of solutions to solve:\n");
scanf("%d",&sudokAmount);
arrayMake();
//sudokuCheck(sudokAmount);
return 0;
}
int arrayMake(){
int j;
int i;
int** sudoArr;
sudoArr = malloc(sizeof(int*) * SIZE * SIZE);
printf("Please Enter Sudoku Solutions(By rows)\n");
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
scanf("%d\n", &sudoArr[i][j]);
}
}
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
printf("%d \n", sudoArr[i][j]);
}
}
return 0;
}
First of all, you allocate memory for the matrix wrong way. Correct will be:
int** sudoArr = (int**)malloc(SIZE * sizeof(int*));
for (int index=0; index < SIZE; ++index)
{
sudoArr[index] = (int*)malloc(SIZE * sizeof(int));
}
Link to online compiler with correct version of your code: correct sources

My 2d array is taking one extra element

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]);

Segmentation fault:11, when I run C code

I am new in C programming. When I write a c code about sorting integers. I got a Segmentation fault: 11. I search the related articles, but seems too confusing for me. Here follows first part of my code(get 10 input integers, and derive all the odd integers). Can you help me?
#include <stdio.h>
int i;
int main(void)
{
int array[10];
int previous[10],odd[10];
printf("Pls enter 10 nums\n");
while(i < 10)
{
scanf("%d", &array[i++]);
}
for(i = 0;i < 10;i++)
{
printf("%d ", array[i]);
}
for(i = 0;i < 10;i++)
{
int a,j;
if(array[i] % 2 == 1)
{
previous[a] = i;
odd[j] = array[i];
a++;
j++;
}
}
}
The problem is with the variables a and j. In C you cannot be sure that when you declare them they will have the value 0.
If you don't give i and a initial values you will likely be attempting to go beyond the bounds of your array.

Strange behavior with simple C function

I have 2 simple functions, one function inputs in the the NxM array not including N+2 and M+2. So the original array must be surrounded by zeros and the other outputs the whole array. When the out function is called I have a very strange output:
But when I move the code to the main function everything is totally fine. I tried compiling this code in CodeBlocks and NetBeans.Behaviour is the same.
I don't know what's going on there. Can somebody explain?
.....
int main()
{
int array[N+2][M+2]={{0}};
local_in(N,M,array);
local_out(N,M,array);
return 0;
}
void local_in(int len, int len2,int arr[][len2])
{
int i;
int j;
for(i = 1; i <= len; i++)
for(j = 1; j <= len2; j++){
scanf("%d",&arr[i][j]);
}
}
void local_out(int len, int len2,int arr[][len2])
{
int i;
int j;
for(i = 0; i < len+2; i++){
for(j = 0; j < len2+2; j++)
printf("%d ",arr[i][j]);
printf("\n");
}
}
Your local_* functions pass the array as int arr[][len2]; but should use int arr[][len2+2] instead.
In general, the code should be much clearer if you passed the correct array dimensions around then implemented any policy on which items to read or write inside the local_* functions.

Resources