Thread: Scanf and Dynamic arrays

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    11

    Scanf and Dynamic arrays

    Any idea why this returns 0 on all the vectors elements?

    Code:
        int n, i;
        scanf("%d", &n);
        float* vectors;
        vectors = new float[n];
        for (i=0; i < n; i++)
          {
           
        scanf("%d", &vectors[i]);
           }
        for (i=0; i < n; i++)
          {
             printf("%f\n", vectors[i]);
           }
    Last edited by no_one_knows; 06-16-2009 at 07:29 PM.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    scanf("%d", vectors[i]);
    vectors[i] is a float, one of n such floats. The scanf function requires you to use the address-of operator (&) when reading data into such a variable.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jun 2008
    Posts
    11
    Yes, I corrected that. Originally it was with the & but got posted like this for some reason.

    Unfortunately, it still doesn't work. All the prints are 0.0000.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Are you really attempting to read a float with %d? Why?

    For that matter, are you really attempting to use scanf in C++? Why?

  5. #5
    Registered User
    Join Date
    Jun 2008
    Posts
    11
    Quote Originally Posted by tabstop View Post
    Are you really attempting to read a float with %d? Why?

    For that matter, are you really attempting to use scanf in C++? Why?
    Duh! It works now, thanks a lot. I should have used the C board.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. 2D Dynamically allocated pointer arrays
    By Lionmane in forum C Programming
    Replies: 37
    Last Post: 06-11-2005, 10:39 PM
  4. String manipulation and scanf vs fgets
    By Nit in forum C Programming
    Replies: 9
    Last Post: 03-20-2002, 12:44 PM
  5. dynamic memory
    By falconetti in forum C Programming
    Replies: 2
    Last Post: 12-21-2001, 02:26 PM