Use new to allocate memory for primitive type : New « Language « C++






Use new to allocate memory for primitive type

Use new to allocate memory for primitive type
#include <iostream>
using namespace std;

int main()
{
  float *f;
  long *l;
  char *c;

  f = new float;
  l = new long;
  c = new char;

  if(!f || !l || !c) {
    cout << "Allocation error.";
    return 1;
  }

  *f = 10.102;
  *l = 100000;
  *c = 'A';

  cout << *f << ' ' << *l << ' ' << *c;
  cout << '\n';
 
  delete f; delete l; delete c;

  return 0;
}


           
       








Related examples in the same category

1.Use new to allocate memory for a class and check errorUse new to allocate memory for a class and check error
2.Pointer for double and use new to allocate memoryPointer for double and use new to allocate memory
3.Demonstrate the new(nothrow) alternative.Demonstrate the new(nothrow) alternative.
4.Handle exceptions thrown by new.Handle exceptions thrown by new.
5.Force an allocation failure.Force an allocation failure.
6.Dynamic int arrayDynamic int array
7.Watch for allocation errors using both old-style and new-style error handling.