Thread: allocate memory dynamically

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    allocate memory dynamically

    hi, i was learning to allocate memory dynamically as and when needed.my 2 codes got errors.

    Code:
    int main(void){
    	int *a;
    	int i=0;
    	for(i=0;i<10;i++){
    		a=new int[1];
    		a[i]=i;
    	}
    }

    Code:
    	char *a;
    	a=new char[1];
    	a="a";
    
    	a=new char[1];
    	a++;
    	a="t";
    
    	cout<<a;  /*expecting a output of at:but only get output of t*/

    if some one can correct my errors,its helpfully enough.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well the first one should have
    a = new int[10];
    outside the loop, and only the assignment inside the loop

    As for the second, look up strcpy, and don't increment 'a', otherwise you'll never know what to delete later on.
    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
    Sep 2006
    Posts
    835
    You need to allocate an array all at once, in a single new statement. Otherwise the memory isn't contiguous. For example your first code snippet should be
    Code:
    int main() {
      int *a;
      int i=0;
      a = new int[10];
      for (i=0; i<10; i++) {
        a[i] = i;
      }
    }

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Hopefully you already know how to use string and vector, which are generally better choices in C++ than dynamically allocating an array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  3. Checking if memory has been dynamically allocated
    By Xzyx987X in forum C Programming
    Replies: 28
    Last Post: 03-14-2004, 06:53 PM
  4. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM
  5. deleting dynamically allocated memory...
    By heljy in forum C++ Programming
    Replies: 2
    Last Post: 09-08-2002, 11:40 AM