Thread: Dynamically Allocated Array

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    99

    Dynamically Allocated Array

    Why is the array not getting properly initialized?

    Code:
    #include<stdio.h>
    
    main(void)
    {
       int *p = malloc(5 * sizeof(int));
       int i=0;
       
       while(i<5)
       {
           *p = i;
           i++;
           p++;                
       }
       
       i=0;
       while(i<5)
       {
             printf("a[%d] = %d\n",i,*p);               
             i++;
       }
         
       getchar();
       return(0);
    }

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    You are shifting the pointer's position in the first while loop and in the second while loop, you are accessing memory you shouldn't access. That's really bad. Do not use pointer arithmetics, prefer using the brackets [] instead with i as an index.

    Edit: Besides, it's int main() and not just main() or void main().

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You also didn't include stdlib.h either.
    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.

  4. #4
    Registered User
    Join Date
    Jun 2007
    Posts
    99
    ok!, it is working now, thanx

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  2. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  3. Destructors in dynamically allocated arrays
    By frenchfry164 in forum C++ Programming
    Replies: 1
    Last Post: 11-28-2003, 11:26 PM
  4. delete dynamically allocated char array
    By xddxogm3 in forum C++ Programming
    Replies: 7
    Last Post: 11-23-2003, 04:57 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM