Sorting a 2d vector, pointer trouble
Hi. Iīm kinda new to the pointer and multidimensional arrays. I need an input for the number and dimensions of an array. Than scan these and, sort the vectors and print them again. Only, every time I run the programm, it gets stuck and stops.
Hereīs my code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void swap (double **p, double **q); /* wissel de pointer waardes om */
double length (double v[], int dim); /* bepaal de lengtes van de vectoren */
int main (void)
{
static int dim, num;
int i, j;
double **w, *v;
scanf ("%d %d", &dim, &num); /* read N and M */
w = calloc (num, sizeof (double *)); /* allocate array of M pointers */
v = calloc (num, sizeof (double ));
for (i = 0; i < num; i++)
{
/* allocate space for N dimensional vector */
w[i] = calloc (dim, sizeof (double));
/* read the vector */
for (j = 0; j < dim; j++)
{
scanf ("%le", &w[i][j]);
}
}
for (i = 0; i < num; i++){
v[i] = length(w[i], dim);
}
/* acces the lengths and swap length and w vector in order*/
for (i = 0; i < num - 1; ++i){
for (j = num - 1; j > i; --j){
if (v[j-1] > v[j])
{
swap(&w[j-1], &w[j]);
}
}
}
for (i = 0; i < num; ++i){
for(j = 0; j < dim; ++j){
printf("%le", w[i][j]);
}
}
return 0;
}
void swap(double **p, double **q)
{
double *tmp = 0;
*tmp = **p;
**p = **q;
**q = *tmp;
}
double length (double v[], int dim)
{
int i;
double wl = 0.0;
for (i = 0; i < dim; ++i)
{
wl += ((v[i]) * (v[i]));
}
wl = sqrt(wl);
return wl;
}
Iīve been stuck on this for quite a while. Thanks in advance!