Dynamically Allocated Array

This is a discussion on Dynamically Allocated Array within the C Programming forums, part of the General Programming Boards category; Why is the array not getting properly initialized? Code: #include<stdio.h> main(void) { int *p = malloc(5 * sizeof(int)); int i=0; ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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, 08:07 AM
  2. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 12:01 AM
  3. Destructors in dynamically allocated arrays
    By frenchfry164 in forum C++ Programming
    Replies: 1
    Last Post: 11-28-2003, 10:26 PM
  4. delete dynamically allocated char array
    By xddxogm3 in forum C++ Programming
    Replies: 7
    Last Post: 11-23-2003, 03:57 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21