unwanted changing value of an array element being address/number of element for the second array in C - c

I have problem that really confuses me a lot. I want to have a sparse matrix stored in 3 arrays and perform matrix/vector multiplication. Matrix and vectorB are red from a file. That's the background. The problem is in unwanted changing the value of an integer array element being an "argument" of the double array. Here is what I am doing:
int row[ELEMENTS_NO] = {0};
int col[ELEMENTS_NO] = {0};
double values[ELEMENTS_NO] = {0.0};
double vectorB[M_SIZE] = {0.0};
double res[M_SIZE]={0.0};
...reading row,col,values, from the file...
printf("\n row[0]:%d, col[0]:%d",row[0],col[0]);
for (k = 0; k < ELEMENTS_NO; k++) {
res[row[k]] = res[row[k]] + values[k]*vectorB[col[k]];
}
printf("\n\n\n row[0]:%d, col[0]:%d",row[0],col[0]);
the output of the first print is correct:
row[0]:1, col[0]:1
while the second print gives me following output:
row[0]:1352932126, col[0]:1
Why the value of col array changed after executing for loop? How to solve my problem and remain row and col elements unchanged?
Thank you for any useful information!

Check the value of row[k] and make sure it's between 0 and ELEMENTS_NO

My best guess is that one of the elements of row is negative, thus res[row[k]] would be negative.
Try running the program using valgrind, this will tell you when you have out of bounds problems for arrays.

You are indexing res[] by a value from the row array. The first one is over 1 billion, so you are changing the (more than) billionth element of res[] which I suspect is beyond the end of the array. Then anything can happen, including overwriting other variables.

Related

Fnd max float number in 2d array (whitout knowing the size of it) on C

I am trying to find a solution in a C programming
I have a 2d array, but i dont know its size
I can only access the array with a array view of [11][11]
The main idea is to find the peak of a mountain (max element)
So basically my 2d array is a map where each index is a float number, corresponding to the height of the mountain
I know i am out of the map when my float number is -1
That is what i was thinking to do, but i cant put it onto a code in a proper way
My solution is based on brute force approach
my basic idea was getting one 2d array formed by myview
what would give me a [11][11] array
then get a max value on that [11][11] array and store it.
next step i would generate another myview array using a loop.
i would apply same process here, to get a max value on that new array
then i would compare myfirst Max value with that second Max value
the value who have the biggest value would be stored on my max variable, with the location as well (point x and point y).
then i would run a loop again to create another myview array, and so on.
My plan to run on all possible [11][11]arrays is:
starting from running a loop for all the columns, but always keeping the rows 1-11
i know there is no more columns when all the values inside of my array [11][11] are -1.0
so when i find that array i would jump for next section of rows (12-23) for example
and again run for all columns.
i also could set a max value per set of a row (so at set of rows 1-11 the max value (peak) is 197.15 , then at set of rows 12-23 the max value (peak) is 397.15, for example)
i know will not be more rows when in my first set of columns i get the values inside of my array [11][11] -1.0000
so i would just need to get my biggest value on all set of rows, then i would get my solution.
You mean you have a two-dimensional array with two lines of eleven elements each, as you would get if you ran int array[11][11];? Then you can have two nested loops, one for (int i = 0; i < 2; i++) and for (int j = 0; j < 11; j++) nested inside each other to loop over the individual elements of the two lines. You have a buffer variable that holds the maximum so far. In your loop you compare each element you're looping over against the buffer variable, and the new element becomes the new buffer variable if it's bigger than the existing one:
void main(void) {
int array[11][11];
int buffer = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; 11 < 2; j++) {
if (array[i][j] > buffer) {buffer = array[i][j];}
}
}
}

Printing an empty 2d Array in C

I am writing a program that takes a 2D array and by use of a switch case, you can direct it to fill with random numbers and/or print the array among other things.
Before I fill the array with random numbers, I go to print the array just to see what it would do and I get this:
176185448 1 1 01430232144
32767180624652332767143023216832767
143023216832767 0 11430232192
32767176185344 1 0 14
143023220832767 0 0 0
0 0 0 0 0
This is my code for the print array function and I am passing plist from main:
void PrintArray2D(int plist[M][N])
{
size_t row, column; //counter
for (row = 0; row < M; ++row)
{
for (column = 0; column < N; ++column)
{
printf ("%5d" , plist[row][column]);
}
printf ("\n");
}
}
My Program is working fine otherwise. When I fill with random numbers and then print, my output is correct. The array size is 6 by 5. I'm just curious as to why, anything is being printed at all when it is supposed to be an empty array. And even more curious as to the specific output I am getting.
You are printing the value of uninitialized array. In this case the behavior of program is undefined. You may get any thing, either expected or unexpected result.
The value you are getting may be the some previous value stored at that location (called garbage value). Your program may gives erroneous result.
Are you initialising the array?
If not, you are more than likely getting the remains of whatever was in memory beforehand.
To initialise it to all zeros quickly, wherever it is defined have something like
int list[M][N] = {0};
Just a warning, the zero does not mean set all values to 0. It sets the first elements to the contents of the curly braces. So:
int values[M] = {1,2,3};
Would set the first three numbers to 1,2, and 3 and the remainder to zeros.
Variables in C must be initialized. If you don't initialize a variable (like an array) it contains some non-logic numbers (like address of a memory unit - the value which had been there before in that location of the memory)
The thing you're printing is that! you can't do this in some languages like Java, if you do so, you get an compilation error.
I hope this helps

Delete a column from a double array

I'm stuck here. I've got a matrix of size NxN stored in a double array. Then I want to delete a given column, lets say the first column. So I created a new double array of size NxN-1 and copy the values from the first matrix to the second one, except the 1st column of course. But then I want to set the first array to be the second array. I am blanking here.
double matrix[N][N]
//fill up the matrix code here...
// remove first column of array
double newMatrix[N][N-1];
for(i = 0; i < N; i++){
for(j = 1; j < N; j++){
newMatrix[i][j-1] = matrix[i][j];
}
}
matrix = newMatrix; // how do I set this correctly? Do I need to realloc the first array?
You cannot assign arrays in C, which I assume that your compiler tells you. To do such dynamic memory management, you will need to use pointers instead of arrays. I suggest you read up on how malloc() and free() work so that you can do what you want.
Edit:
Another solution comes to mind if you are only removing columns (or rows): keep track of the number of rows and columns used in the array. Then you can remove a row or column within the original array without creating a copy first. Just move the data past the delete column (or row) to the left (or up) then decrement your size counters. (I hope this make sense. If not let me know and I'll elaborate.)
like Code-guru said malloc() and free() should help alot, but if u simply wanted to delete the last column the you wouldn't need two arrays:
double matrix[2][3] = {1,2,3,4,5,6}; //declaring a 2 by 3 matrix
for (i=0;i<2;i++) //rows
{
for (j=0;j<3-1;j++) //columns - 1
{
printf("%.1f ",matrix[i][j]); //I chose to display matrix...
}
printf("\n");
}
Instead of accessing elements from array[i][j], one might opt to access elements from array + stride_x[x] + stride_y[y]; where array is originally introduced as double matrix[N*N]; or double *matrix = malloc(sizeof(double)*N*N);.
The stride_y[x] would originally contain offsets of columns for all rows: 0 1 2 3 4 ... N-1 and stride_y[y] would contain similar offsets multiplied with original row width 0 N 2*N 3*N..
From these 1-D arrays one can more effortlessly delete or exchange complete rows and columns, which may come handy in eg. recursive implementation of determinant calculation / Gauss Jordan elimination.

Why is this array not big enough?

I have been running this random walk simulation for a while now and I keep getting an error EXC_BAD_ACCESS from Xcode. Its printing out a large part of the simulation though.
I think its running out of memory for some reason but I am not sure why.
If I go towards the end of the array I edited it so I don't get within 100 spaces of the edge (by editing the variable steps to steps -100). This works but I would like to know whats going on.
Any help would be appreciated.
double** places;
places = (double**) malloc(steps*sizeof(double*));
for (int i = 0; i < steps; i++)places[i] = (double*) malloc(2*sizeof(double));
for (i = 0; i< steps/*, exit*/; i++) {
// Find the angle of movement
angle = getRand()*360;
// Take a step
xPos+= STEP*cos(angle);
yPos+= STEP*sin(angle);
//Write Step to array
places[i][1] = xPos;
places[i][2] = yPos;
//Write Step to File
fprintf(ff, "%d %lf %lf\n",i,xPos,yPos);
}
Array indexes start at zero.
Did you mean to write this?
places[i][0] = xPos; //Zeroth element is considered the first element
places[i][1] = yPos; //Second element
You've allocated an array of the proper size (steps x 2), but you're writing to the wrong offsets on the sub-arrays. They should be [0] and [1], not [1] and [2].
[2] is actually the 3rd array element, so you're writing outside of the subarray's bounds.
The inner arrays (located at places[i]) have space for two elements - indexed by [0] and [1], since array indices generally start at zero in C. Here, you index them with [1] and [2]. You need to use [0] and [1] instead, or allocate enough space for three elements (and waste the space allocated for [0]).
Indexing starts from 0.
This should be:
places[i][0] = xPos;
places[i][1] = yPos;
You're off by one. Arrays in C are zero-based, so the first element is at position 0. You need to change your assignment to the places array as follows:
// Write Step to array
places[i][0] = xPos;
places[i][1] = yPos;

C two dimensional array smallest gets biggest instead

I am new to stackoverflow as am new to programming, yet am not really a 'professional and enthusiast programmer'. Enthusiast maybe but not professional...
In a part of some beginner code of mine i have a two dimensional array diff[i][j], where the value is zero wherever i==j. I am trying to get the smallest value in each row but not the zero value...
the part of the code (under construction) that searches the smallest of the first row is:
i=1;
double smallest;
for ( j=1 ; j<=n ; j++ )
{
smallest = diff[i][j];
if ( j!=i && diff[i][j] < smallest )
smallest = diff[i][j];
}
printf("\n %lf\n", smallest);
however, the result is always the biggest number not the smallest. Anyone knows why??
P.S. I'd be thankful for any suggestion or comment of dealing with stackoverflow.com and the way i asked my question, since am new here... thank you in advance...
EDIT
after the answers below, i decided to make the i=1 a special case and make two separate functions for both cases... however, when i try to assign j to other variable i failed... in the previous code:
if (j!=i && diff[i][j]<smallest) {smallest=diff[i][j]; d=j}
declared d previously and everything... when i print d it prints a random number >maybe the memory location content... tried for debugging to assign an initial value - with the declaration - and when printing it came out the initial value... the point is i want d to hold the column where the smallest value is... how can i acheive that??
You never initialize smallest
i=1;
double smallest = diff[1][2]; // initialize it to a non-diagonal element in the column
for (j=1; j<=n; j++)
if (j!=i && diff[i][j]<smallest){
smallest=diff[i][j];
}
printf("\n %lf\n", smallest);
EDIT:
You also seem to have { smallest= diff[i][j]; .. } in your code that overrides the value of smallest each iteration. I removed it in my answer.
First thing, array indexes start from 0 in C, not 1, so you should have j = 0; j < n, assuming n is the size of the array.
Then, you assign to smallest every time around the loop, not just if the new value is smaller. So, what you're seeing is the last value.
Assuming that you really do run one past the end of the row, this "last value" is probably actually the first value in the next row. Or some arbitrary value stored in the memory that just so happens to be past the end of the array, if your array has exactly 2 rows. Anyway, it's Undefined Behavior to read past the end of an array, which is Not Good. Anything is allowed to happen, and what does happen often is more puzzling than you expect.
Careful about your array indexes. In C array indexes start at zero.
For:
double array[10];
you would go through all ten elements with:
int i;
for( i = 0; i < 10; i++ )
printf( "The array value at %d is %g\n", i, array[i] );

Resources