How to initialize array elements before using it? - c

I have to write a program which illustrates the usage of pointers with arrays and functions.
#include <stdio.h>
#include <conio.h>
#define ROWS 3
#define COLS 4
void print(int rows, int cols, int *matrix);
void main(void)
{
int a[ROWS*COLS],i;
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
The above program prints a matrix with the rows and columns predefined. I want to modify the program such that the rows and columns are entered by the user.
#include <stdio.h>
#include <conio.h>
void print(int rows, int cols, int *matrix);
void main(void)
{
int ROWS,COLS,a[ROWS*COLS],i;
printf("Enter the number of rows: ");
scanf("%d",ROWS);
printf("\nEnter the number of columns: ");
scanf("%d",COLS);
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
This programs is giving an error that the variables ROWS and COLS are being used before they are being declared. How to solve this problem.

One option is to allocate a on the heap:
int main(void)
{
int rows,cols,*a,i;
printf("Enter the number of rows: ");
scanf("%d",&rows);
printf("\nEnter the number of columns: ");
scanf("%d",&cols);
a = malloc(rows*cols*sizeof(int));
for(i=0;i<rows*cols;i++)
{
a[i]=i+1;
}
print(rows,cols,a);
getch();
free(a);
}
Notice also that I've:
Added ampersands that were missing from the scanf() calls;
Changed the return type of main() to int. See What are the valid signatures for C's main() function?
As you why your code didn't work:
Traditionally, C required constant expressions for array bounds. When ROWS and COLS were constants, everything was good with your code. Once you've turned them into variables, a became a variable-length array. The problem was that the size of the array is computed at the point where the array is declared, and at that point the values of ROWS and COLS were not yet known.
In C99, it is possible to fix your code by pushing the declaration of a down:
int main(void)
{
int rows,cols,i;
printf("Enter the number of rows: ");
scanf("%d",&rows);
printf("\nEnter the number of columns: ");
scanf("%d",&cols);
int a[rows*cols];
for(i=0;i<rows*cols;i++)
{
a[i]=i+1;
}
print(rows,cols,a);
getch();
}

printf("Enter the number of rows: ");
scanf("%d",&ROWS);
printf("\nEnter the number of columns: ");
scanf("%d",&COLS);

You should declare the array after you get rows and cols - otherwise it's not make sense.
int rows,cols;
scanf("%d %d",&rows,&cols);
int a[rows*cols];
By the way, main should return int (0 if the program ends successfully)

You need to dynamically allocate the array - use malloc
scanf("%d", &ROWS); - notice the & - scanf requires the address.

Related

C function to fill an array with strings from user input

I am stuck on a programming assignment in C. The user has to enter a number specifying the size of an array no bigger than 10 elements which will store the names of students. This must be done in a separate function from the main function called getNames. Each name can be up to 14 characters and getNames must be invoked from within the main function. Here is my code:
#include <stdio.h>
void getNames(char *a, int n){
int i;
for(i=0; i<n; i++){
printf("Enter a name: ");
scanf("%s", &a[i]);
}
}
void printNames(char *a, int n){
int i;
for(i=0; i<n; i++){
printf("%s\n", &a[i]);
}
}
void main(){
int num; //number of names in array 'names'
printf("Num of students: ");
scanf("%d", &num);
char names[num][15]; //each name is 14 characters plus
//a null character
getNames(names[num], num);
printNames(names[num], num);
}
The code compiles and runs without syntax errors but the array is not filled correctly. For example:
Num of students: 5
Enter a name: Jeb
Enter a name: Bob
Enter a name: Bill
Enter a name: Val
Enter a name: Matt
returns:
JBBVMatt
BBVMatt
BVMatt
VMatt
Matt
Clearly there is an issue writing to the array but I am not sure what it is.
For this assignment our professor was adamant that we cannot use any global variables. His wording was rather vague about how we should implement this. My first thought would be to move the for loop in getNames into the main function and just calling getNames repeatedly but I would like a solution that incorporates that into getNames. I'm new to C, having mostly dealt with Java so please bear with me. Any help would be appreciated.
If the code you have posted is exactly the code you are using, then it is invoking undefined behavior by accessing a memory location that your program does not own: getNames(names[num], num);.
Array indexing in C goes from 0 to n-1. (or from names[0]-names[num-1]) Same in other similar calls.
next issue is the function prototypes to accommodate;
char names[num][15];
The function needs to send the address of an array of arrays. See edits on code to show the difference.
Next issue are the following statements, see comments after each
getNames(names[num], num);//names[n] points to memory beyond what is owned.
//should point to address of beginning of memory &names[0]
printNames(names[num], num);//ditto
Working code example, see edits to explain:
//void getNames(char *a, int n){//change *a to either a[][15] or (*a)
void getNames(char a[][15], int n){
int i;
for(i=0; i<n; i++){
printf("Enter a name: ");
scanf("%s", a[i]);
}
}
//void printNames(char *a, int n){ //change *a to either a[][15] or (*a)
void printNames(char a[][15], int n){
int i;
for(i=0; i<n; i++){
printf("%s\n", a[i]);
}
}
void main(){
int num; //number of names in array 'names'
printf("Num of students: ");
scanf("%d", &num);
char names[num][15]; //each name is 14 characters plus
//a null character
//getNames(names[num], num);//names[n] points to memory beyond what is owned.
//printNames(names[num], num);//ditto
getNames(&names[0], num);
printNames(&names[0], num);
}
you can do following
Method
in main function call as below
getNames(names, num);
printNames(names, num);
and change the functions as below
void getNames(char (*a)[15], int n)
{
...
}
void printNames(char (*a)[15], int n)
{
...
}
Method , in main calls remain same
void getNames(char a[5][15], int n)
and
void printNames(char a[5][15], int n)
But instead of using hard values better to use #define row and col sizes

How do I get input for an array from a user in C programming?

I am new to C and I've run into a bit of a problem when it comes to user input for an array.
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
return 0;
}
It does not matter what value I set for n. It always prompts the user 4 times.
As mentioned in comments, you must change this:
/* bad */
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
into this
/* good */
printf("Number of scores: ");
scanf("%d", &n);
int score [n];
This since C executes code from top to bottom like when you are reading a book. It will not "double back" a few rows above and fill in n once it has been entered by the user. At the point where you declare int score [n], n must already be known.
If your using an array with unknown size during compilation, I would suggest using memory allocation. So the user determines the array size while running the program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int *score;
printf("Number of scores: ");
scanf("%d", &n);
score = (int *)malloc(sizeof(int)*n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
free(score)
return 0;
}
The malloc function allocates memory with the size of n and returns a pointer to the allocated memory.

Why this program stops working at runtime?

It successfully compiles.
But at running on getting values of matrix it crashes stops working.
#include <stdio.h>
void getmat(int mat[100][100],int m,int n);
void matmul(int mat1[100][100],int mat2[100][100],int m1,int n1,int m2,int
n2,int matmul[100][100]);
void printmat(int matmul[100][100],int m,int n);
int main(void)
{
int m1,n1,m2,n2;
printf("Enter the dimensions of matrix1: ");
scanf("%d %d",&m1,&n1);
printf("Enter the dimensions of matrix2: ");
scanf("%d %d",&m2,&n2);
int mat1[m1][n1];
int mat2[m2][n2];
int matmul1[m1][n2];
int matmul2[m2][n1];
printf("For the values of matrix 1\n");
getmat(mat1,m1,n1);
printf("For the values of matrix 2\n");
getmat(mat2,m2,n2);
if(n1==m2)
{
printf("Mat1 x Mat2 is possible.");
matmul(mat1,mat2,m1,n1,m2,n2,matmul1);
printf("Mat1 x Mat2 :\n");
printmat(matmul1,m1,n2);
}
else
printf("Mat1 x Mat2 is not possible.\n");
if(n2==m1)
{
printf("Mat2 x Mat1 is possible.");
matmul(mat2,mat1,m2,n2,m1,n1,matmul2);
printf("Mat2 x Mat1 :\n");
printmat(matmul2,m2,n1);
}
else
printf("Mat2 x Mat1 is not possible.\n");
return 0;
}
void printmat(int matmul[100][100],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d ",matmul[i][j]);
}
printf("\n");
}
}
void getmat(int mat[100][100],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter element of %dx%d: ",i+1,j+1);
scanf("%d",&mat[i][j]);
}
}
}
void matmul(int mat1[100][100],int mat2[100][100],int m1,int n1,int m2,int
n2,int matmul[100][100])
{
int i,j,k;
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
matmul[i][j]=0;
for(k=0;k<m2;k++)
{
matmul[i][j]+=mat1[i][k]*mat2[k][j];
}
}
}
}
Help making any changes or optimizing this code.
Also another way to this.
This error shows up at running a half
Use a Debugger
Also, all your functions are written to take a 100x100 matricies.
But you declare your matricies to have variable sizes:
int mat1[m1][n1];
int mat2[m2][n2];
int matmul1[m1][n2];
int matmul2[m2][n1];
When you pass a 3x3 matrix to a function that is expecting a 100x100 matrix, you will definitely have a bad time.
I see that you are setting up your arrays with variable sizes. You should really set it up as a very large array or use malloc to set up the array properly. When you call the processing routines, pass the arrays as pointers and use the sizes as arguments in order to set up your references. You should note that myarray[i, j] is the equivalent of a single valued array using i*rowsize + j. When you define your array in the subroutines as [100, 100], it will go to [i*100 + j] which is outside the bounds of your actual array.
This causes the program to crash.
Once you actually calculate everything properly, it should work.

Error while calculating sum of two matrices in c

So I'm new to C and was trying to write a program to add two matrices
program 1
#include <stdio.h>
int main(){
int m,n,o,p,i,j;
int mat1[m][n];
int mat2[m][n];
int result[m][n];
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
printf("enter elements of matrix one :");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%i",&mat1[i][j]);
}
}
printf("enter the elements of matrix two:");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%i",&mat2[i][j]);
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("the sum of the matrices are");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%i",result[i][j]);
}
}
return 0;
}
this produced no error
method two
when i used a function to enter the values in two the matrix, it produced the following error
25 24 C:\Users\Hp\my-programs\matrix-entry-function.cpp [Error] invalid types 'int[int]' for array subscript
25 35 C:\Users\Hp\my-programs\matrix-entry-function.cpp [Error] invalid types 'int[int]' for array subscript
code:
#include <stdio.h>
int mat_entry(int m,int n)
{
printf("enter the rows and columns of matrix ");
scanf("%i%i",&m,&n);
int mat[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("\nenter the %i'th element %i'th row :",j+1,i+1);
scanf("%i",&mat[i][j]);
}
}
}
int main()
{
int a,b,c,d,e,f,m,n;
int res[m][n];
int mat1=mat_entry(a,b);
int mat2=mat_entry(c,d);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
res[i][j]=(mat1[i][j]+mat2[i][j]);
}
}
}
Your program 1 happened not to produce error. You are unlucky. You invoked undefined behavior by using values in uninitialized variables having automatic storage duration, which are indeterminate. You must declare mat1, mat2 and result after reading m and n.
int main(){
int m,n,o,p,i,j;
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
/* move these declaretions after reading number of rows and columns */
int mat1[m][n];
int mat2[m][n];
int result[m][n];
printf("enter elements of matrix one :");
Your program 2 invokes undefined behavior by using return values of functions with no return statements. Also using [] operator with two operands having type int is wrong. E1[E2] is equivalent to (*((E1)+(E2))) (N1570 6.5.2.1 Array subscripting, paragraph 2), so exactly one operand of it must be a pointer (including one converted from arrays).
To return matrixes as return values of functions, consider using structures and allocating memory for elements dinamically.
You have used
int mat1=mat_entry(a,b);
int mat2=mat_entry(c,d);
instead of sending parameters from one function to another, which would work only when the variables you take are pointers, here you have to either use mat1 and mat2 as pointers or you have to make them integer matrices.
There isn't one thing that you are doing wrong my friend.
You are not even using dynamic memory allocation but still trying to declare matrices with values which are not defined yet.Try to run your code,even your first code won't run.
i have corrected your code for you :
#include <stdio.h>
int main(){
int m,n;
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
int mat1[m][n];
int mat2[m][n];
int result [m][n];
int i,j;
printf("enter elements of matrix one :");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&mat1[i][j]);
}
}
printf("enter the elements of matrix two:");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("the sum of the matrices are");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d",result[i][j]);
}
}
return 0;
}
I don't think it would be that difficult to put this functionality into a function . Try it out
It is impossible to write a function that makes a matrix with user-supplied dimensions, unless you use dynamic allocation (which you probably don't want to, at this stage).
Luckily, you don't need that! Since all you want is adding matrices, they should have the same dimensions, and you only want to ask the user once what the dimensions are. Afterwards, fill both matrices, and do the "adding" part.
That is:
int main()
{
int a,b,c,d,e,f,m,n;
printf("enter the rows and columns of matrix ");
scanf("%i%i",&m,&n);
int res[m][n];
int mat1[m][n];
int mat2[m][n];
mat_entry(m, n, mat1); // fill matrix 1
mat_entry(m, n, mat2); // fill matrix 2
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
res[i][j]=(mat1[i][j]+mat2[i][j]);
}
}
}
The function mat_entry has no return value (i.e. void), but it receives the matrix to fill by pointer (the details are a bit complicated, but the syntax is straightforward):
void mat_entry(int m,int n, int mat[m][n])
{
...
}
The code inside is the same as you suggested, minus the asking for dimensions:
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("\nenter the %i'th element %i'th row :",j+1,i+1);
scanf("%i",&mat[i][j]);
}
}

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++)

Resources