Reputation: 37
I am writing some code to convert a matrix into a unique vector. There are some conditions on the elements to be inserted in the vector, so I first run a test to determine what number of elements in each column that will go into the vector. For that, I create a samples[] array with "number of columns" elements, and element k in this array represents the number of elements I will be transferring to the vector from column k.
The code is as follows:
#include<stdio.h>
#include <stdlib.h>
#define INVISIBLE 999
void main()
{
int i,j;
int l=6, c=2;
double testmat[6][2]={
{3,9},
{4,7},
{2,5},
{6,10},
{2,6},
{5,8}
};
printf("Our sample matrix\n");
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
printf("%.0f\t",testmat[i][j]);
printf("\n");
}
unsigned long size=0;
int samples[c];
double vect[size];
for(j=0;j<c;j++)
{
i=0;
while((testmat[i][j]!=INVISIBLE) && (i!=l))
{
i++;
size++;
}
samples[j]=i;
}
printf("Size = %d\n",size);
printf("Samples:\n");
for(j=0;j<c;j++)
printf("samples[%d] = %d\t",j,samples[j]);
printf("\n");
int counter = 0;
for(j=0;j<c;j++)
for(i=0;i<6;i++) //Tried to put i<samples[j] but given the new value of samples[j] ...
{
printf("samples[%d]=%d\n",j,samples[j]);
vect[counter]=testmat[i][j];
counter++;
// printf("(%d,%d)\t",i,j);
}
}
I am quite lost as why the samples[] array changes by divine intervention ... any help/explanation will be much appreciated
Upvotes: 0
Views: 81
Reputation: 45736
Note these lines:
unsigned long size=0;
double vect[size];
You're using a variable length array (which is generally discouraged), but more importantly, you're saying that vect
has a length of 0
; it can't store anything.
This is a problem because later you do:
vect[counter]=testmat[i][j];
You're writing into an 0-length array. This will overwrite memory on the stack. Apparently here, you end up overwriting data in samples
. What will get overwritten though depends entirely on how the compiler chosen to place data on the stack, and how far off the end of the array you tried to access. It's undefined.
If you're going to write into vect
, it must have enough space to hold the data ahead of time.
Apparently even declaring a 0-length array invokes undefined behavior, so it's difficult to say which part exactly is responsible here for your data being overwritten. Definitely don't write off the end of an array though. Clobbering data on the stack won't lead to good times unless you like breaking things for malicious/educational purposes.
Upvotes: 3
Reputation: 35154
You are writing beyond the size of an array, which is undefined behaviour. One of such (undefined) behaviour could be that other memory areas are changed:
// this creates an array of size 0:
unsigned long size=0;
double vect[size];
...
// here you are writing to it:
vect[counter]=testmat[i][j];
Upvotes: 1