Thread: Need Help with malloc

  1. #1
    Registered User
    Join Date
    Oct 2015
    Posts
    2

    Need Help with malloc

    I'm trying to write a program that allows the user to enter in the size of the array, then the values of the elements and then print them out. After running it the program prints out the memory locations instead of the values and then errors out.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
     
     
    int main()
    {
        int size;
        int i;
        int *ptr;
       // int val;
     
     
        printf("Enter number of elements: ");
        scanf("%d",&size);
     
        ptr= malloc(size*sizeof(*ptr));  //memory allocated using malloc
        if(ptr==NULL)
        {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Enter elements of array: \n");
        for(i=0;i<size;++i)
        {
            scanf("%d",ptr[i]);
     
        }
     
        for(i=0;i<size;i++)
        {
     
            printf("%d : %d.\n", i+1, ptr[i]);
     
        }
     
        free(ptr);
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > scanf("%d",ptr[i]);
    Surprised it doesn't crash on you - you forgot the &

    Try using -Wall when you compile.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2015
    Posts
    2
    Quote Originally Posted by Salem View Post
    > scanf("%d",ptr[i]);
    Surprised it doesn't crash on you - you forgot the &

    Try using -Wall when you compile.
    Thanks after adding the & it worked. Why do we always miss the obvious?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using malloc
    By zafy in forum C Programming
    Replies: 5
    Last Post: 11-12-2012, 08:12 PM
  2. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  3. Replies: 7
    Last Post: 10-01-2008, 07:45 PM
  4. How do i use malloc?
    By Josh Kasten in forum C++ Programming
    Replies: 4
    Last Post: 02-24-2003, 11:44 PM
  5. I need help with Malloc()
    By electrolove in forum C Programming
    Replies: 3
    Last Post: 02-03-2003, 12:07 AM