Program crash while trying to print a bidimensional array - c

as the title says, my program crashes when i try to print a bidimensional array.
The error is surely printf in function printarray, but i couldn't understand why it lead to crash.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array[n][m],n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}

If an array dimension has size N then the valid range of indices is [0, N - 1].
So the loops in the function should look like
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i< col;i++){
//printf("lol3 %d",i);
for( j=0; j<row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
The same is valid for loops in main.
This call of the function invalid
printarray(array[n][m],n,m);
There shall be
printarray(array,n,m);
Take into account that such a declaration of an array like
int array[COL][ROW];
is very confusing. It would be more correctly to write
int array[ROW][COL];
^^^ ^^^
Also it is not clear what is the meaning of variables p and q in this loop
does not make sense
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
It seems that this loop is from some other program.:)
And you have to check that n and m are not greater than ROW and COL.
Also it is a bad idea to mix l'Italian with English.:)

The posted code does not cleanly compile, for several reasons.
1) missing
#include <time.h>
2) function main() ALWAYS returns 'int' so a proper main statement would be: 'int main( void )'
3) the first parameter to 'printarray()' is defined to be a pointer to a 2 dimensional array.
However,
a) the actual call passes the contents of a specific 'cell' in the array.
b) the passed 'cell' is beyond the end of the array.
Suggest: 'printarray( array, n, m )' as the calling statement.
Note, in C, an array name degrades to the address of the first entry in the array.
4) an array should be defined as arrayName[numRows][numColumns].
This will become much more important when declaring an array of pointers where each pointer will point to the contents of the associated row.
In the posted code, the definition/naming is backwards from typical.
in Memory, an array is laid out left to right (the columns) then top to bottom (the rows).
The 'biggest' index is rows and should be listed first.
5) to avoid text replacement problems, numeric values in macros should be wrapped in parens.
6) as a suggestion, appropriate vertical spacing (blank line) between code blocks makes the code much clearer and more understandable by us humans
7) when calling scanf() (and family of functions) always check the returned value (not the parameter values) to assure the operation was successful
8) consistent indentation makes the code much easier to read/understand by us humans, suggest: indent 4 spaces after every opening brace '{' and un-indent before every closing brace '}'. Note: Never use tabs for indenting. Different environments have different tab widths and/or different tab stops.
9) for readability, and to make debug much easier, only place one statement per line of code. This applies to declaring variables, so they can be easily commented and applies to executable statements

here i am attaching the your program without any error. the problem was to calling the printarray function.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array,n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}

Related

Reading and Printing a matrix

I tried to read and print a matrix using an external function (from another c file), the thing is that I want to read the matrix dimensions in the function and store them in the main function, how can I do this?
Do I need to return an array with the m and n dimensions of the matrix or can I access the variables that I created in main and change their value within the external function? (I prefer if someone would explain the second) I don't actually know how to use pointers and stuff.
Sorry for my English, I'm not a native speaker, also thanks for your response
The second and the third functions are in an external function.c file
int main(){
int num_of_rows, num_of_columns;
int matrix[10][10];
read_matrix(num_of_rows, num_of_columns, matrix);
print_matrix(num_of_rows, num_of_columns, matrix);
printf("\n Press any key to exit the program: ");
_getch();
return 0;
}
void read_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
printf("\nPlease specify the number of rows:");
scanf("%d", &num_of_rows);
printf("\nPlease specify the number of columns: ");
scanf("%d", &num_of_columns);
printf("\nPlease introduce the matrix elements below:\n");
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
void print_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= %d", i, j, matrix[i][j]);
}
}
}
Parameters are passed by value in C.
In read_matrix, the num_of_rows parameter is a local variable. Even if you modify it, the caller won't see anything change. Same for num_of_columns.
You want this:
void read_matrix(int *num_of_rows, int *num_of_columns, int matrix[10][10]) {
// ^ add * ^ add *
...
scanf("%d", num_of_rows); // << remove the &
printf("\nPlease specify the number of columns: ");
scanf("%d", num_of_columns); // << remove the &
...
for (i = 0; i < *num_of_rows; i++) {
// ^add *
for (j = 0; j < *num_of_columns; j++) {
// ^add *
and in main:
read_matrix(&num_of_rows, &num_of_columns, matrix);
// ^ ^ add the &s
This is basic knowledge that is covered in your C learning material. Most likely in the chapter dealing with pointers and the one dealing with function calls.
Here's the catch. I tested your code and it works nicely. The problem is, what you want to achieve is only possible by using dynamic memory allocation. Take a look at the malloc and free functions.
You can read more about it on:
https://www.tutorialspoint.com/what-is-malloc-in-c-language
https://www.tutorialspoint.com/how-do-malloc-and-free-work-in-c-cplusplus
In C language you are responsible for allocation a space in memory for variable length data structures. Pointers just store an address to a specific memory space allocated to the desired data type.
e.g.:
int n, *p;
p = (int*) malloc(n * sizeof(int));
In this example, you are just giving p an address to the first integer from n integers you just allocated.
p will work just like a vector when using for loops because behind the scenes, it's exactly what happens when you traverse your fixed length vectors and matrices, but this time you were in control of it's length in runtime.
#include<stdio.h>
void main()
{
int x[3][3], p, q, max;
printf("Enter the elements of matrix: \n");
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
scanf("%d", &x[p][q]);
}
max=x[0][0];
printf("The matrix is as follows: \n");
for(p=0;p<3;p++)
{
for(q=0;q<=3;q++)
scanf(" %d", &x[p][q]);
}
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
{
if(x[p][q]>max)
max=x[p][q];
}
printf("\n");
}
printf("Maximum number in the matrix is: %d", max);
}
Output:
Enter the elements of matrix:
23 65 12
12 23 56
12 10 32
The matrix is as follows:
23 65 12
12 23 56
12 10 32
Maximum number in the matrix is: 65
Matrix Programs
Explore more matrix programs.

Read a list of n numbers and make an array in C

So I want to take an input such as this:
The first input tells us the size of the array and the second line contains the numbers of array like this:
input:
3
1 2 3
And I want to make an array from the second input line with a size of from the first input line.
I currently have:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n;
scanf("%d", n);
int x[n];
int y[n];
}
But after which I get stumped.
If you have a VLA(Variable Length Array) supporting compiler(eg. GCC):
int n;
scanf("%d", &n);
int arr[n];
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
and if not,
int n;
scanf("%d", &n);
int *arr = malloc(n * sizeof(int));
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
This code uses the functionality of scanf to be able to take multiple delimited input.
If you have to take n inputs and not only set the size of arr to n, do this:
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &n[i]);
}
It should be apparent that VLA functionality lets you to make an array on the stack with a runtime value. Otherwise, you'll need to allocate it on the heap with malloc().
What if there are more than 3 numbers to scan. Do I need to add more
"%d" and arr[] or is there some way for it to work with any number of
numbers in the second line.
To address this point you can go with iterating over loop
for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
}

How to read a bidimensional array inside a function?

i have this code how to read the bidimensional array using a function?
i write this function it works read all the numbers but when i output to console the array there are not the values that i entered
ex
Input:
2 1 2 3 4
Output:
16 256
1 4525376
#include <stdio.h>
#include <stdlib.h>
void citMat(int a, int n) {
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf("a[%d][%d]",i,j);
scanf("%d", &a);
}
}
int main()
{ int i,j;
int a[10][10],n;
printf("Introdu n:");
scanf("%d", &n);
citMat(a[10][10],n);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
You need to change the prototype to (Here array dimension is important)
void citMat(int a[10][10], int n)
Other changes are explained by others (The whole code is below)
#include <stdio.h>
#include <stdlib.h>
void citMat(int a[10][10], int n) {
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("a[%d][%d]:",i,j);
fflush(stdout);
scanf("%d", &a[i][j]);
}
}
int main()
{ int i,j;
int a[10][10],n;
printf("Introdu n:");
scanf("%d", &n);
if (n > 10)
{
fprintf(stderr, "Invalid input %d\n", n);
return 1;
}
citMat(a,n);
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
1. If you want to pass a 2-d array to function .Change your function definition to -
void citMat(int a[10][10], int n) { // first parameter to take a 2-d int array
2. And then inside function citMat to take input-
scanf("%d", &a[i][j]); // you need to write like this
Note -
1. Array indexing starts from 0 , so if you have array a[n] then it have valid index from 0 to n-1 .
So start reading from 0 and till n in all for loops . If you include n then you would access index out of bound and writing to it will cause undefined behaviour.
So, look out for that .
2. int main() -> int main(void) or int main(int argc,char **argv)
You need to change few things in your program to make it work
1) Call the function with the base address of the array, lik
citMat(a,n);
2) Change your function definition to,
void citMat(int a[10][10], int n)
to make it accept 2D array as parameter.
3) Change the scanf() to read for each element,
scanf("%d", &a[i][j]);
4) Since the array index starts from 0, change all the for loops termination condition to
for(i=1;i<n;i++)

Can anybody resolve my mistake

I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()

Changing the values in a number array in C

I want to make a program that uses a function I created where it swaps all the elements of an array X (that has the length of N) with some number K, only if that element is greater than K. Where am I going wrong here?
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K);
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("%d",X[i]);
}
}
int swap_K(int *X, int K)
{
int i;
for (i=1; i<=sizeof(X)/sizeof(int); i++){
if (X[i]>K)
X[i]=K;
}
return X;
}
In swap_K(int *X, int K), sizeof(X) is sizeof(int *), not the size of the array.
In C, a pointer is not really the same as an array.
To fix it, use N instead of sizeof(X)/sizeof(int) everywhere, esp. inside swap_K().
1) Arrays start with index 0.
2) In your main function you don't need to use sizeof(X)/sizeof(int) in for loop as you already know it is equal to N.
3) When you pass the array to the function, you are sending the base address of the array which decays into pointer, so in swap_K function, sizeof(X) will return sizeof(int) which is 4(generally).
To overcome this you should send the size of your array from main function. For example: swap_K(X,K,N);
4) You don't need to return X from swap_K as you are sending the base address of X from main function.
For example:
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=0; i<N; i++)
{
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K,N);
for (i=0; i<N; i++)
{
printf("%d",X[i]);
}
}
int swap_K(int *X, int K,int N)
{
int i;
for (i=0; i<N; i++)
{
if (X[i]>K)
X[i]=K;
}
//return X; //This is not required
}
Your loop is incorrect
for (i=1; i<=sizeof(X)/sizeof(int); i++)
It should be
for (i=0; i<N; i++)
There are several problems with the code posted:
arrays in C are 0-indexed, so the for loops should ALWAYS iterate from 0 to N - 1. Iterating past N is a buffer overflow
the pointer to the array is just the pointer to the first element of the array. The swap function can't know if the pointer passed to it is part of an array or a single value. With this in mind it will need to take another argument which tells what is the size of the passed in array as pointer. Iteration inside the loop will use that value instead of sizeof(X) / sizeof(int) = 1
you're defining X as a variable sized array which is allocated entirely on the stack. Introducing a reasonably large N will crash your program. It would be better to allocate the array in the heap if you don't know what the size of the input will be.

Resources