Sorting vectors based on length in C - c

I want to make a programm that takes the dimension and numbers of vectors to be sorted based on their length.
Most of the code works but the sort part of the program doesnt.
Basically what I want to do there is: compare the output from the bereken_lengte function from 2 places in the array w. But nothing seems to happen.
Also in the function bereken_lengte, I cant take the roots of the sum after the loop ended.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double bereken_lengte(double *array, int dim)
{
int i, j;
double sum = 0.0;
for(i=0; i<dim; ++i)
sum += pow(array[i],2);
return sum;
}
void swap(double **p, double **q)
{
double *tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
void sort_vector(double *w[] , int num , int dik )
{
int i,dim,j;
dim = dik;
for(i=0;i<num;++i)
for(j = 1+i;j<num;++j)
{
if(bereken_lengte(w[i],dim) > bereken_lengte(w[j],dim) )
swap(&w[i], &w[j]);
}
}
int main (void)
{
int dim, num;
int i, j,k,l;
double **w;
scanf ("%d %d", &dim, &num); /* read N and M */
w = calloc (num, sizeof (double *)); /* allocate array of M pointers */
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 ("%lf", &w[i][j]);
}
}
sort_vector(w,num,dim);
for(k=0; k<num; ++k)
{
printf("\n");
for(l=0; l<dim; ++l)
printf("%f ", w[k][l]);
}
return 0;
}

double bereken_lengte(double *array, int dim)
{
unsigned int i;
double sum =0.0;
for(i=0; i<dim; ++i)
sum += pow(array[i],2);
return sum;
}
Just initialise the sum to zero before summing.
BTW I changed i to unsigned. It is IMnsvHO a good habit to use unsigned types for index && size variables (they won't underflow, and if the do, you'll notice it)
UPDATE:
This tries to avoid the int indices and sized, and uses qsort. (rather ugly, because the compare function takes only two elements; don't try this in a multithreaded program ...) Note, I may have rows and columns interchanged, but thats a way of life... gewoon, omdat het kan!:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double bereken_lengte(double *array, size_t dim)
{
size_t i;
double sum=0.0;
for(i=0; i<dim; ++i)
sum += pow(array[i],2);
return sum;
}
/* this is ugly: qsort only allows only two arguments */
static size_t ze_third_argument=0;
int srt_pdbl(void *l, void *r)
{
double **dl = l, **dr = r;
double diff;
diff = bereken_lengte( *dl, ze_third_argument) - bereken_lengte( *dr, ze_third_argument) ;
return (int) diff;
}
void sort_vector(double *w[] , size_t num , size_t dik )
{
ze_third_argument = dik;
qsort(w, num, sizeof *w, srt_pdbl );
}
int main (void)
{
size_t dim, num;
size_t i, j,k,l;
double **w;
scanf ("%zu %zu", &dim, &num); /* read N and M */
w = calloc (num, sizeof *w); /* allocate array of M pointers */
for (i = 0; i < num; i++)
{
/* allocate space for N dimensional vector */
w[i] = calloc (dim, sizeof *w[i] );
/* read the vector */
for (j = 0; j < dim; j++)
{
scanf ("%lf", &w[i][j]);
}
}
sort_vector(w,num,dim);
for(k=0; k<num; ++k)
{
printf("\n");
for(l=0; l<dim; ++l)
printf("%f ", w[k][l]);
}
return 0;
}

Related

Printing a 2-D array in a function in C

I want to initialise and print a 2-D array in two separate functions, but i don't really know if i am doing this correctly.
I wrote 2 functions: int** matrix_initialization(int n, int m) and int print_matrix(int n1, int n2, int **a);
In the first function i have to arguments: int n - the number of rows and int m - the number of cols. In this function i initialise a pointer to the pointer int **matrix = NULL; Then i allocate memory to it, and giving this 2-D array random values.
Is that okay that the type of the int** matrix_initialization(int n, int m) function is int ** ?
The second function is int print_matrix(int n1, int n2, int** a) and there are some problems, the main is that it is not working. I have three arguments int n1 - rows, int n2 - cols, int** a a pointer to the pointer. This function is to print matrix.
Here is my code:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <time.h>
int** matrix_initialization(int n, int m)
{
int** matrix = NULL;
matrix = (int**)malloc(n * sizeof(n));
if (matrix != NULL)
{
if (matrix != NULL)
{
for (int i = 0; i < m; i++)
{
*(matrix + i) = (int*)malloc(m * sizeof(m));
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = rand() % 20 - 5;
}
}
}
}
return matrix;
}
int print_matrix(int n1, int n2, int** a)
{
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < n2; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
int main()
{
srand(time(NULL));
int N, M, **a;
scanf_s("%d %d", &N, &M);
a = matrix_initialization(N, M);
print_matrix(N, M, a);
}
There are many issues with this code.
Major:
You aren't using 2D arrays but arrays of pointers. That doesn't make the slightest sense for this application, you are just making your code more complex, error prone and slow for absolutely nothing gained. See Correctly allocating multi-dimensional arrays.
matrix = (int**)malloc(n * sizeof(n)); Both of your malloc calls are strange, n is just a size parameter (could as well be size_t) and not necessarily of the same type as the data. Which is a int* in this case, not an int. You should be allocating something like matrix = malloc(n * sizeof(*matrix))
The first for loop for (int i = 0; i < m; i++) is wrong, should be n.
You aren't freeing allocated memory.
Minor:
locale.h isn't needed for this program.
There's no actual need to initialize your pointer matrix to NULL if you are to assign to it on the next line. Also you have multiple redundant checks vs NULL.
*(matrix + i) is never the best way to access an array in C, it's just an obscure way of writing matrix[i]. Don't complicate things just for the heck of it.
Don't name parameters n and m in one function and then n1 n2 in another function. Don't complicate things just for the heck of it.
Avoid functions ending with _s unless you have specific reasons why you need to use them. They are non-portable. It's very likely that whoever told you to use it has no idea what they are talking about. Including no idea about the whole "bounds-checking interface" debacle in C11.
int main() is obsolete style, always use int main (void) (as opposed to C++).
Here is a rewrite with all problems fixed, using 2D arrays instead:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void* matrix_initialization (int n, int m)
{
int (*matrix)[m] = malloc( sizeof(int[n][m]) );
if (matrix != NULL)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = rand() % 20 - 5;
}
}
}
return matrix;
}
void print_matrix (int n, int m, int a[n][m])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
int main (void)
{
srand(time(NULL));
int N, M;
scanf("%d %d", &N, &M);
int (*a)[M];
a = matrix_initialization(N, M);
print_matrix(N, M, a);
free(a);
}
You have two major problems:
The first is
malloc(n * sizeof(n))
which is the same as
malloc(n * sizeof(int))
And that makes no sense when you want to create an array of n pointers to int. On a 64-bit system it's unlikely that sizeof(int) == sizeof(int *).
It should be
malloc(n * sizeof(int*))
Or better yet
malloc(n * sizeof *matrix)
The second problem is your loop where you allocate the int arrays:
for (int i = 0; i < m; i++)
You have just created an array of n elements. Now you iterate over m elements? This will only work if n == m.
The correct loop should of course be
// Iterating over an array of n elements
for (int i = 0; i < n; i++)
You also have the same problem with the malloc call as mentioned above, but this time it just so happens to work because m is an int which is the right type and size.
On another few notes, in C you should not cast the result of malloc.
You never free any of the data you allocate, leading to memory leaks.
And instead of *(matrix + i) use matrix[i].
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <time.h>
int** matrix_initialization(int n, int m)
{
int** matrix = NULL;
//matrix = (int**)malloc(n * sizeof(n));
matrix = (int**)malloc(n * sizeof(int *));
if (matrix != NULL)
{
for (int i = 0; i < n; i++)//here is n,not m
{
matrix[i] = (int*)malloc(m * sizeof(int));
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = rand() % 20 - 5;
}
}
}
return matrix;
}
int print_matrix(int n1, int n2, int** a)
{
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < n2; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
return 0;
}
int main()
{
srand(time(NULL));
int N, M, **a,i;
scanf("%d %d", &N, &M);
a = matrix_initialization(N, M);
print_matrix(N, M, a);
//free all the memory
for (i = 0; i<N; i++) {
free(a[i]);
}
free(a);
return 0;
}

Can somone please explain this to me

For n=3 and a={1,2,3},b={4,5,6} its supposed to calculate 1*4+2*5+3*6.
I don't understand why does it work because p is a pointer and p=produs(a,b,n) means that the address of p becomes the value returned by produs.
#include <stdio.h>
#include <conio.h>
void citire(int *x,int *n)
{
for(int i=1; i<=*n; i++)
scanf("%d",&x[i]);
}
int produs(int *a,int*b,int n)
{
int produs=0;
for(int i=1;i<=n;i++)
produs=a[i]*b[i]+produs;
return produs;
}
int main()
{
int n;
int*p;
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
int *b=(int*)malloc(n*sizeof(int));
citire(a,&n);
citire(b,&n);
p=produs(a,b,n);
printf("%d",p);
return 0;
}
When you do:
size_t size = 10;
int* x = calloc(size, sizeof(int));
You get an array x with 10 items in it, indexed 0..9, not 1..10. Here calloc is used to make it abundantly clear what's being requested instead of doing multiplication that can be mysterious or obtuse.
As such, to iterate:
for (int i = 0; i < size; ++i) {
x[i] ...
}
You have a number of off-by-one errors in your code due to assuming arrays are 1..N and not 0..(N-1).
Putting it all together and cleaning up your code yields:
#include <stdio.h>
#include <stdlib.h>
void citire(int *x, size_t s)
{
for(int i=0; i < s; i++)
scanf("%d", &x[i]);
}
int produs(int *a, int* b, size_t s)
{
int produs = 0;
for(int i = 0; i < s; i++)
produs = a[i] * b[i] + produs;
return produs;
}
int main()
{
int n;
scanf("%d",&n);
int* a = calloc(n, sizeof(int));
int* b = calloc(n, sizeof(int));
citire(a, n);
citire(b, n);
// produs() returns int, not int*
int p = produs(a,b,n);
printf("%d", p);
return 0;
}
You're using pointers in places where pointers don't belong. In C passing a pointer to a single value means "this is mutable", but you don't change those values, so no pointer is necessary nor advised.
Try and use size_t as the "size of thing" type. That's what's used throughout C and it's an unsigned value as negative indexes or array lengths don't make any sense.

Adding 2 matrices using pointers

I can acheive it by passing (c,a,b) to add_mat function, where result of a,b is stored in c like,
void add_mat(int c[][3], int a[][3], int b[][3], int m, int n)
What should be the return type of add_mat if I want to construct the funtion in this way
?? add_mat(int a[][3], int b[][3], int m, int n)
Below is a sample code
#include<stdio.h>
void read_mat(int a[][3], int m, int n){
//scan data
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
printf("[%d][%d] : ",i,j);
a[i][j]=i+j;
}
}
}
int* add_mat(int a[][3], int b[][3], int m, int n){
int c[3][3];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
c[i][j]=a[i][j]+b[i][j];
}
}
return c;
}
int main(){
int a[3][3];
int m=2,n=2; //mxn of a matrix
read_mat(a, m, n);
//add
int b[3][3];
read_mat(b, m, n);
int* c[3][3];
c = add_mat(a,b,m,n);
return 0;
}
Like passing or pointing the calculated value c inside add_mat function to variable in main function.
You cannot do that, since the memory of the c matrix will be gone when the function terminates.
You need to dynamically allocate it with malloc(), in order for the memory not to be free'd, unless you call free(). I have some examples for that in 2D dynamic array (C), if you want to take a look.
With your previous function, you would create the matrix c outside the function (in main()), that's why dynamic memory allocation was not required.
PS: You should compile with warnings enabled:
prog.c: In function 'add_mat':
prog.c:19:12: warning: returning 'int (*)[3]' from a function with incompatible return type 'int *' [-Wincompatible-pointer-types]
return c;
^
prog.c:19:12: warning: function returns address of local variable [-Wreturn-local-addr]
prog.c: In function 'main':
prog.c:32:7: error: assignment to expression with array type
c = add_mat(a,b,m,n);
^
prog.c:31:10: warning: variable 'c' set but not used [-Wunused-but-set-variable]
int* c[3][3];
^
Here is a working example, which is just for demonstrative purposes:
#include <stdio.h>
#include <stdlib.h>
void read_mat(int a[][2], int n, int m){
//scan data
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
a[i][j] = i + j ;
}
}
}
int **get(int N, int M) /* Allocate the array */
{
/* Check if allocation succeeded. (check for NULL pointer) */
int i, **table;
table = malloc(N*sizeof(int *));
for(i = 0 ; i < N ; i++)
table[i] = malloc( M*sizeof(int) );
return table;
}
void print(int** p, int N, int M) {
int i, j;
for(i = 0 ; i < N ; i++)
for(j = 0 ; j < M ; j++)
printf("array[%d][%d] = %d\n", i, j, p[i][j]);
}
void free2Darray(int** p, int N) {
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
int** add_mat(int a[][2], int b[][2], int m, int n){
int** c = get(n, m);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
c[i][j]=a[i][j]+b[i][j];
}
}
return c;
}
int main(){
int n = 2, m = 2; //nxm of a matrix
int a[n][m];
read_mat(a, n, m);
//add
int b[n][m];
read_mat(b, n, m);
int** c;
c = add_mat(a, b, n, m);
print(c, n, m);
free2Darray(c ,n);
return 0;
}
Output:
array[0][0] = 0
array[0][1] = 2
array[1][0] = 2
array[1][1] = 4
PPS: If you really want to use static arrays, then I recommend using int c[3][3]; add_mat(c, a, b, m, n);
Oh yes, the pointers ...
In C, locally declared arrays usually are allocated on the stack (not on the heap) which means they are not valid outside the respective scope.
In other words, in your function add_mat(), c technically can be returned, but the address it points to will only contain meaningful matrix data as long as the function is executed.
After having returned from the function, the return value of the function is a pointer which still contains (points to) the address where the matrix was stored during execution of the function, but the contents of that location, i.e. the matrix data, can contain arbitrary garbage now.
So what you are doing is technically possible (i.e. throws no compile errors), but is definitely not what you want.
Secondly, your line int* c[3][3]; probably is not what you intend it to be. You are declaring c to be a two-dimensional array (matrix) of pointer to int here. This is not correct since you want to process int values, but not pointers to int values (which are addresses).
To solve both problems, just write int c[3][3]; instead of int* c[3][3]; and change your add_mat() function as follows:
void add_mat(int a[][3], int b[][3], int c[][3], int m, int n){
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
c[i][j]=a[i][j]+b[i][j];
}
}
}
Then call that function like that:
add_mat(a,b,c,m,n);
In your code add_mat returns the pointer to the variable which lives while the function executes only. You can accomplish your goal with dynamically allocated matrix.
In C it is common to pass a dynamically allocated matrix via pointer to pointers to the rows of matrix as a first parameter:
void foo(int** matrix, size_t m, size_t n);
Here matrix is a pointer to the array of pointers. Every pointer in this array points to the row of matrix. So, matrix[0] points to the array containing the first row of matrix.
And it is common to use size_t type for any sizes of arrays.
If you need create matrix dynamically, be careful with memory. Every dynamically allocated block should be released. Otherwise you will get memory leaks, that may cause the program crash. Therefore, when you allocate rows of matrix, you should check if allocation of current row was successfull. If not, you should release all previously allocated rows.
There is a working code for your question:
#include <stdio.h>
#include <stddef.h>
#include <malloc.h>
void free_mat(int** a, size_t m) {
if (!a) {
return;
}
for (size_t i = 0; i < m; ++i) {
free(a[i]);
}
free(a);
}
int** create_mat(size_t m, size_t n) {
int** rows = calloc(m, sizeof(int*));
if (!rows) {
return NULL;
}
for (size_t i = 0; i < m; i++) {
rows[i] = malloc(n * sizeof(int));
if (!rows[i]) {
free_mat(rows, m);
return NULL;
}
}
return rows;
}
void read_mat(int** a, size_t m, size_t n) {
for (size_t i = 0; i < m; i++) {
for (size_t j = 0; j < n; j++) {
printf("[%d][%d]: ", i, j);
scanf("%d", a[i] + j);
}
}
}
void print_mat(const int* const* a, size_t m, size_t n) {
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
printf("[%d][%d]: %d\n", i, j, a[i][j]);
}
}
}
int** add_mat(const int* const* a, const int* const* b, size_t m, size_t n) {
int** c = create_mat(m, n);
if (c) {
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
}
return c;
}
int main() {
size_t m = 3;
size_t n = 3;
int** a = create_mat(m, n);
int** b = create_mat(m, n);
if (!a || !b) {
printf("error when allocating matrix\n");
}
else {
read_mat(a, m, n);
read_mat(b, m, n);
int** c = add_mat(a, b, m, n);
if (!c) {
printf("error when allocating matrix\n");
}
else {
print_mat(c, m, n);
free_mat(c, m);
}
}
free_mat(a, m);
free_mat(b, m);
return 0;
}
But you would be more flexible, if add_mat didn't create a new matrix.
It is common to pass a pointer to the result matrix as a function parameter:
void add_mat(int** c, const int* const* a, const int* const* b, size_t m, size_t n);

crash on trying to reallocate a pointer using pointer to this pointer

I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).

storing input into malloc array (1d and 2d) and printing

I am tryin to take input from the user and store it into an array and print it out: i have 2 functions:
/* Read a vector with n elements: allocate space, read elements,
return pointer */
double *read_vector(int n){
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
vec[i] = n;
return vec;
}
and the print function is:
void print_vector(int n, double *vec){
int i;
for (i = 0; i < n; i++) {
printf("%d\n", vec[i]);
}
}
the main function is:
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n);
void print_vector(int n, double *vec);
void free_vector(double *vec);
int main(){
int n;
double *vector;
/* Vector */
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%d", &n);
printf("Enter %d reals: ", n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n,vector);
free_vector(vector);
}
when i run this, it does not let me enter any numbers, it just skips it and prints out 0's. How do i fix this?
Try the code below. You're almost certainly either not compiling with warnings, or ignoring the warnings. All warnings mean something, and to a beginner they all matter. With gcc use the -Wall option, or even -pedantic.
As halfelf pointed out, you need a scanf in your read loop but it needs to be a pointer (&vec[i]). Always return something at the end of main. Also check the return value of malloc, it could fail and return a null pointer.
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) {
printf("Enter number %i of %i: ", i + 1, n);
scanf("%lf", &vec[i]);
}
return vec;
}
void print_vector(int n, double *vec)
{
int i;
for (i = 0; i < n; i++) {
printf("%f\n", vec[i]);
}
}
void free_vector(double *vec)
{
free(vec);
}
int main()
{
int n;
double *vector;
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%i", &n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n, vector);
free_vector(vector);
return 0;
}
In the read_vector(int n) function's for loop:
for (i=0; i<n; i++)
vec[i] = n; // this should be scanf("%lf",vec+i) to read input from stdin
and notice your { and } there. If there's only one line in the loop, { and } is not necessary, OR you have to use a pair of them. The return clause must be out of the loop.
Btw, add return 0 at the end of your main function.
simple..you forgot to write scanf..!
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
scanf("%d",&vec[i]);
return vec;
}

Resources