2

I have a problem with my code. I am creating a dynamic array and ask for some values. But when I print them on screen, the array seems uninitialized.

int main(void)
{
    int i, j;
    double *p;
    printf("How much numbers?\n");
    scanf("%d", &i);
    p = malloc (sizeof(double)*i);
    for(j = 0; j < i; j++)
    {
        printf("Set nr. %d :\n", j);
        scanf("%f", p+j);
    }
    for(j = 0; j < i; j++)
    {
        printf("Nr. %d = %f\n", j, *(p+j));
    }
}

I think the problem should be in this line, but i cannot figure out why?

scanf("%f", p+j);

I also tried this versions of code:

scanf("%f", (p+j));
scanf("%f", &p[j]);

Thank you!

honiahaka10
  • 772
  • 4
  • 9
  • 29
  • Possible duplicate of [Problems with scanf and doubles](https://stackoverflow.com/questions/19890748/problems-with-scanf-and-doubles) – phuclv Sep 09 '18 at 04:42

3 Answers3

3

You have wrong format specifier for reading a double:

    scanf("%f", p+j);

Use %lf for reading a double:

    scanf("%lf", p+j);

Your possible confusion arises from the fact that printf() uses %f for printing both float and double while scanf() needs different format specifier. Read this post:

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
0

Your problem is double *p. You need an array of pointers to type double:

double **p;

You sill need to do something like this:

int main(void)
{
    int i, j;
    double **p;
    printf("How much numbers?\n");
    scanf("%d", &i);
    p = (double **)malloc (sizeof(double*)*i);
    for(j = 0; j < i; j++)
    {
        printf("Set nr. %d :\n", j);
        p[j] = (double *)malloc(sizeof(double));
        scanf("%lf", p[j] );
        printf ("p[%d]: %f\n", j, *p[j]);
    }
    for(j = 0; j < i; j++)
    {
        printf("Nr. %d = %f\n", j, *p[j]);
    }
    return 0;
}
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 2
    His original code allocates memory correctly, I don't see why you want to expand a 1-d array to 2-d. And you have added bogus casts to malloc. – M.M May 27 '14 at 21:45
0

Use this:

scanf("%f", p+(j*sizeof(double));

The pointer p stores the address for the first element of the array. The second element will be at the address:

[First Address] PLUS one element. The elements you want are double so there you go!

TheCrafter
  • 1,909
  • 2
  • 23
  • 44
  • 3
    no... adding `1` to a pointer makes it point to the next element, regardless of element size. `p+j` (aka. `&p[j]`) is correct. – M.M May 27 '14 at 21:49