0

I have a C code and wanna save data x and y but only I get a zero values into this pointer array

#include <stdio.h>
#include <stdlib.h>


int main(){
    int n;
    //Ingreso el numero de puntos
    printf("Numeros de puntos: ");
    scanf("%i", &n);
    //Asignacion de memoria para los puntos x y y
    double *x= (double*) calloc(n,sizeof(*x));
    double *y= (double*) calloc(n,sizeof(*y));
    //Ingreso de datos 
    printf("Ingrese los puntos x,y: ");
    for(int i = 0 ; i < n ; i++){
        scanf("%d", &x[i]);
        scanf("%d", &y[i]);
    }
    for(int j = 0 ; j < n ; j++){
        printf("\n%.3f, %.3f", *(x+j),*(y+j));
    }
    //Libero memoria de x y y
    free(x);
    free(y);
    return 0;

}

When I print anything with n numbers I get this n output (number of points equals 2)

0.000, 0.000
0.000, 0.000
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • When you use `scanf` you use `x[i]` and `y[i]`, but for `printf` you use `*(x + j)` and `*(y + j)`... Why this inconsistency? Pick one way and stick with it (I recommend array-indexing with e.g. `x[j]` and `y[j]`). – Some programmer dude Dec 04 '19 at 14:23
  • Also note that in C you [don't have to cast the result of `malloc` and its siblings (like `calloc`)](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Dec 04 '19 at 14:25
  • I am learn pointers and I wanted to using differents ways to access it. – Sotireus98 Dec 04 '19 at 14:32

1 Answers1

3

You have mismatch in the conversion specifier (%d - matching an integer and expecting the argument as pointer to integer) with the type of the argument (pointer to a double). This invokes undefined behaviour.

So, instead of

    scanf("%d", &x[i]);
    scanf("%d", &y[i]);

you should use

    scanf("%lf", &x[i]);
    scanf("%lf", &y[i]);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261