C programming error.2Darrays - c

I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected.
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int arr[a][1];
int i,j,k,sum=0;
for(i=0;i<a;i++)
{
scanf("%d",&arr[i][0]);
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);
}
for(j=0;j<a;j++)
{
arr[j][1]=0;
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);//Different Values
}
}

int arr[a][1]; There is only one column and not two.You should use
int arr[a][2];

Here you write out of bounds
arr[j][1]=0;
This is because you write to the second element of an array with only one element.
The size of arr[x] (for any valid x) is just one.
Writing out of bounds leads to undefined behavior.

Your arrays should be something like this :
arr[row][col] where row denotes the number of rows and col the no of coloumns.
Therefore arr[a][1] is a array of a rows and 1 coloumn and therefore your code works wrong.
Your array should be a[a][2]. It means arr is a array with a rows and 2 coloumn.Similarly you have to change the other arr[][] 's throughout the code.

Related

I m trying to build a 2*2 array but my program asks for 5 inputs. Why?

I couldn't zero down where i have missed in the input statement. I have build it to acquire four values as input but it goes one more.
manipulating the array entries to check if the fifth value is stored. Basic things
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
You have declared this
int a[2][2];
which has four items, a[0][0], a[0][1], a[1][0] and a[1][1].
However, you are starting your indexing at 1 and going up to 2, so are stepping out of bounds which is undefined behaviour.
Anything can then happen.
Change your loops i.e.:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
to index from 0.
You also need to consider your printf statement, since that oversteps too.
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=0;i<2;i++) /*go through rows - arrays in c go [0- (n-1)]*/
{
for(j=0;j<2;j++)/*go through col */
scanf("%d",&a[i][j]); /*remove \t- now will scan 4 values only */
}
printf("\n%d\t%d\n%d\t%d", a[0][0],a[0][1],a[1][0],a[1][1]);
return 0;
}

convert an array to multi dimensional C without using pointer

First of all, I would like to know if its possible. If so, please checkout my code and tell me what is wrong.
int m[n]; // this is where I pass the values to a array
for(int i=0;i<n;i++) {
scanf("%d",&a);
m[i]=a;
}
int v[n][b]; // this is where I pass the values from a array to a 2d array
for(int i=0;i<n;i++) { // but for some reason it doesnt work
for(int j=0;j<b;j++) {
v[i][j]=m[i];
}
}
}
The output is :
something like this
v[0][0]:0
v[0][1]:0
v[1][0]:1
v[1][1]:1
....
but I want something like this:
v[0][0]:0
v[0][1]:1
v[1][0]:2
v[1][1]:3
without repeating the values
P.S- if I need to use pointers you can also explain me that way but I would prefer the first one.
In assigning to v[i][j], you are constantly reassigning whatever value was in m[i].
Instead try:
v[i][j] = m[i*n + j];
This is only going to work if the array m has n*b elements.
i*n represents the row you're working on, and j is the column. Or vice-versa, it's up to you how you imagine it.
#include <stdio.h>
int main(){
int m[6]; // this is where I pass the values to a array
int i;
int j;
int k;
int a;
for(i=0;i<6;i++) {
scanf("%d",&a);
m[i]=a;
}
k=0;
int v[2][3]; // this is where I pass the values from a array to a 2d array
for(i=0;i<2;i++) { // but for some reason it doesnt work
for(j=0;j<3;j++) {
v[i][j]=m[3*k+j]; // 3 is the maximum i value [n of your code]
}
k++;
}
return 0;
}
Just used OP's code and changed:
1) Defined all integer variables.
2) the int inside the for removed to be compatible code with every c compiler (OP doesn't really need this changes)
3) Added a variable k that been increased with the changes of outer loop variable and used it in the command v[i][j]=m[3*k+j]; to give the appropriate m value to the new array. (3 been explained in the comment of the same line)
See #Pablo's comment for not using k
Assuming you have at least as many elements in your 1D array as your 2D array and you want to fill in your 2D array in row major order, it suffices to just increment an index for your 1D array every time you read an element from it.
int v[n][b];
int k = 0;
for(int i=0;i<n;i++) {
for(int j=0;j<b;j++) {
v[i][j]=m[k++];
}
}

Addition of sparse matrix using structure in c(triplet form)

I am currently doing a problem of addition of sparse matrices. I am making sparse matrix by using triplet form. The triplet form is made by using structure in c.
struct sparse
{
int row;
int col;
int val;
};
but while doing this sparse matrix problem I encountered a problem that my code only displays the correct sparse matrix when i am giving the indices of nonzero values in increasing order (eg. (0 1 3),(1 2 5),(2 2 7) etc)otherwise it is displaying incorrect matrix.for example if am giving input like (0 1 3),(2 2 7),(1 2 5) etc then it is displaying wrong matrix. How to solve this problem so that in any order of indices it will give correct output?
I have added my input and resulting output. I have done this for two sparse matrix.
#include<iostream>
#include<cstdio>
struct sparse
{
int row,col,val;
};
void readmat(sparse sp[])
{
printf("enter total number number of rows ,column of matrix and total
of nonzero values in this\n");
scanf("%d %d %d",&sp[0].row,&sp[0].col,&sp[0].val);
printf("now start entering the values by specifying index
position\n");
for(int i=1;i<=sp[0].val;i++)
scanf("%d %d %d",&sp[i].row,&sp[i].col,&sp[i].val);
}
void displaymat(sparse sp[])
{
int k=1;
for(int i=0;i<sp[0].row;i++)
{
for(int j=0;j<sp[0].col;j++)
{
if(k<=sp[0].val&&i==sp[k].row&&j==sp[k].col)
{
printf("%d\t",sp[k].val);
k++;
}
else
printf("0\t");
}
printf("\n");
}
}
int main()
{
struct sparse sp1[10],sp2[10],sp3[10];
printf("for first matrix\n");
readmat(sp1);
printf("for second matrix\n");
readmat(sp2);
displaymat(sp1);
printf("\n\n");
displaymat(sp2);
printf("\n\n");
displaymat(sp3);
return 0;
}`
Updating the original answer:
The reason out of order values are not getting printed is because when the value in triplet form points to an element further down the for loops go past all the other values that could have been printed. For example in your example the 3rd element is at row=1, col=3 however the 2nd element is at row=2,col=2. This will lead to the outer for-loop advancing down to 2nd row. At that point in time the loops will not go back and print 1st row.
One way will be to sort based on the row and col and then print the values.

Moving columns in a bidemensional array in C

Hello I have a bidimensional array initiated the following way:
#include <stdio.h>
#include <stdlib.h>
int main(){
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
system("pause");
}
And I need to move the columns, ordering alphabetically the first line,
I mean, the line that contains {'F','H','V','D','U'}.
I need the following output:
char matriz[6][5]={
{'D','F','H','U','V'},
{'U','E','L','E','Q'},
{'S','P','E','E','R'},
{'A','V','E','A','R'},
{'N','L','C','Z','A'},
{'Z','A','Z','Z','Z'}};
I know I need to use the selective ordering method and a cycle of fors, but I am not sure how.
Declare a struct:
typedef struct{
colChar:char;
colIndex:int;
} COL_HEADER;
Make an array of them, same length as row length:
COL_HEADER myColHeaders[5];
Load up each in a loop, colChar as the column header char, colIndex as the column index, 0-4.
Now you can qsort the array with a comparison function that just compares the colChar. The colIndex keeps track of the initial columns. You now know which col needs to go where in the output.
You can then use a couple of loops to copy the source columns to a 'dest' [6][5], using the myColHeaders[5].colIndex to identify the destination column for each source column.
First you have to compare the first elements of each column to all other top elements,if a column's 1st element is greater than the next column's top element then swap both columns.You can also use qsort function in the algorithm header for sorting.
Below is the implementation:
#include <stdio.h>
int main(){
int i,k,j;
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
for(i=0;i<4;i++)
{
for(k=i+1;k<5;k++)
{
//comparing top elements of columns
if(matriz[0][i]>matriz[0][k])
{
//swapping columns
for(j=0;j<6;j++)
{
int t=matriz[j][i];
matriz[j][i]=matriz[j][k];
matriz[j][k]=t;
}
}
}
}
//display
for(i=0;i<6;i++)
{
for(k=0;k<5;k++)
printf("%c ",matriz[i][k]);
printf("\n");
}
}

Weird behavior of a counter inside the for loop

I've noticed that a counter(avariable) of the for loop, doesn't works well.
Indeed, the counter doesn't decrements correctly; I know this question seems stupid , but I can't understand why the a variable does this.
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=2;a>=0;a--) {
for (b=2;b>=0;b--) {
matrice[a][b]=scanf("%d",&i);
}
}
return 0;
}
You are going out of bounds when you read into your array.
for (a=2;a>=0;a--) {
Array has only two elements, yet you try to read into the third on the first iteration.
matrice[2]
Is the third element. This happens for both dimensions.
scanf() call is not correct. It reads the value into i, but it returns the number of read items, not the value of i.
if you are trying to read the numbers into the matrix, then this is what you are supposed to do..
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
scanf("%d",&matrice[a][b]);
}
As the array matrice[2][2] has 2*2 elements, the valid indices are 0 and 1.
Thats why the for loop should start from 1 and not 2
1) The array index start from 0, as per your code it will access matrice[2][2] which will cause undefined behavior.
2) matrice[a][b]=scanf("%d",&i); will store the return value of scanf in matrice[a][b].
#include <stdio.h>
int main() {
int a,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--)
{
for (b=1;b>=0;b--)
{
scanf("%d",&matrice[a][b]);
}
}
//Then print or do other operations on matrice
return 0;
}
You are starting out of bounds.
For an array of size n you iterate from 0 to n-1
So what you want is
for (a=1;a>=0;a--){
for (b=1;b>=0;b--){
}
}
But one word of warning with running backwards with for loops. As is you are fine because you are using integers but if you were to do something like this
for (auto i = some_vector.size()-1;i>=0;i--){
}
You would be in a lot of trouble since i would not be able to take negative values as some_vector.size() is of type unsigned so the loop would never exit. I tend to always increment in a loop for this reason unless the logic dictates otherwise.
Your matrix has a size of [2][2] but you are using a loop that runs from 2 to 0 (inclusive). In an array of size 2 the maximum permissible index is 1.
I guess that you are just learning basic stuff.. so try to run this slightly version of your code:
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--) {
printf("a->%d\n", a);
for (b=1;b>=0;b--) {
printf(" b->%d\n", b);
scanf("%d",&matrice[a][b]);
}
}
printf("Check:\n");
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
printf(" [%d][%d]:%d\n", a, b, matrice[a][b]);
}
}
return 0;
}
In the first loop, the modified code run through the correct indices that for a 2x2 array are (0,0),(0,1),(1,0) and (1,1).
Please note that I have also modified the scanf part using the correct syntax: link.
The second loop is a simple test that what you've coded the data insertion correctly, by outputting the content of the matrix.

Resources