allocate memory dynamically

This is a discussion on allocate memory dynamically within the C++ Programming forums, part of the General Programming Boards category; hi, i was learning to allocate memory dynamically as and when needed.my 2 codes got errors. Code: int main(void){ int ...

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

  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,317
    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, 08:32 AM
  3. Checking if memory has been dynamically allocated
    By Xzyx987X in forum C Programming
    Replies: 28
    Last Post: 03-14-2004, 05: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

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