2

I want 2, 4, 6 to display... instead I think address numbers are displaying?

What do I need to do to correct and why? Thanks

(purpose... to demonstrate ability to change array space and still keep the base of the array)

    int *line;

    line = new int;
    line[0] = 2;
    line = new int;
    line[1] = 4;
    line = new int;
    line[2] = 6;
    line = new int;
    printf("%d  %d  %d", line[0], line[1], line[2]);
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 4
    Well you're sure clobbering that heap good.. Not to mention the FOUR memory leaks trying to display THREE numbers... – Blindy Sep 02 '11 at 16:45
  • http://augustcouncil.com/~tgibson/tutorial/arr.html – Rook Sep 02 '11 at 16:49
  • If you want to "change the array space and keep the base" (I suppose you mean the "initial segment"?), you won't get around copying the old array into a newly allocated area. By the way, there's a class called `std::vector` which does precisely that for you ;-) – Kerrek SB Sep 02 '11 at 16:55
  • 2
    Let me guess, you come from a background in java or c#? – Rob K Sep 02 '11 at 17:02

5 Answers5

7

Try this instead:

int *line;

line = new int[3];
line[0] = 2;
line[1] = 4;
line[2] = 6;
printf("%d  %d  %d", line[0], line[1], line[2]);
delete[] line;

Points to notice:

line = new int[3]; // here you are supposed to specify the size of your new array
...
delete[] line; // whenever you use new sometype[somevalue]; 
               // you must call delete[] later on to free the allocated resources.

Also take a look at this question in SO:

delete vs delete[] operators in C++

Community
  • 1
  • 1
yms
  • 10,361
  • 3
  • 38
  • 68
3

You're overwriting the pointer line at each new int. And you're leaking the memory from the one before it.

Also, since you're only allocating one int, only line[0] is defined. Accessing line[1] and line[2] is undefined.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
2

You declare an int* and allocate an int with new. At this point line contains an address that points to the int.

Accessing line[1] and line[2] are crashes waiting to happen because those locations contain garbage. You never allocated memory at those places.

John
  • 15,990
  • 10
  • 70
  • 110
2

Repeat after me: "This is not Java. I will not use new without good reason."

For an array of three ints, you just want something like:

int line[] = {2, 4, 6};

To print them out, you normally want to use std::cout instead of printf:

std::cout << line[0] << " " << line[1] << " " << line[2];

Note, in particular, that there's no reason to use new for this task at all.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

The line line = new int replaces the thing line points to with a newly allocated piece of the stack of size int.

Luke
  • 7,110
  • 6
  • 45
  • 74